python中的curl执行失败

时间:2017-07-05 13:47:29

标签: python-3.x perl subprocess

我想下载大约300个项目的文件。一个例子如下:

curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1' -b cookies > Absrep1.xml

这将打开页面并下载内容并将其作为xml文件存储在我的最后

我尝试使用系统命令在perl中执行批处理脚本,例如

system('curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1'
-b cookies > Absrep1.xml');

但是,它没有用。有语法错误,我猜这是由于单引号。

我尝试使用python,

import subprocess
bash_com = 'curl "http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1" '
subprocess.Popen(bash_com)
output = subprocess.check_output(['bash','-c', bash_com])

它不起作用。我收到错误,文件不存在。即使它有效,我怎么能包括

  

-b cookies> Absrep1.xml'

参与其中?

请帮忙。在此先感谢,

AP

2 个答案:

答案 0 :(得分:2)

在Perl中,你应该可以使用它:

system(q{curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1' -b cookies > Absrep1.xml});

但是,您最好使用LWP或甚至HTTP::Tiny(除非您需要Cookie),而不是使用外壳。对于更高级的用途,还有WWW::Mechanize

答案 1 :(得分:2)

语法错误几乎肯定是系统调用中的引号:

system('curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1' -b cookies > Absrep1.xml');

单引号要么需要转义,要么可以使用替代括号,例如双引号或带q或qq的自定义括号,例如:

system(q{curl 'http://genome.jgi.doe.gov/ext-api/downloads/get-directory?organism=Absrep1' -b cookies > Absrep1.xml});

从给定的上下文中很难说,但是在perl或python中包含curl调用可能不是最佳方法。 Perl有LWP,Python有请求,而bash shell已经配备齐全,可以运行简单的批处理作业。除非有充分的理由不这样做,否则最好坚持使用一名翻译。