我尝试使用python子进程获取curl命令的输出。但输出是空的。以下是我的源代码:
def validateURL(url):
p = subprocess.Popen("curl",
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
shell = False)
p.stdin.write("http://validator.w3.org/check?uri=" + url + "\n")
p.stdin.close()
stdout_data = p.stdout.read()
print stdout_data
result = re.findall("Error", stdout_data)
print result # empty here
if (len(result) != 0):
return 'ERR'
else:
return 'OK'
为什么呢? PS:我在我的mac os上运行这段代码,然后使用Python 2.7。
答案 0 :(得分:1)
删除stderr = subprocess.PIPE,
,然后查看curl
打印的错误消息。相应地采取行动解决它。
一个可能的原因是URL应该被指定为命令行参数,而不是stdin:
p = subprocess.Popen(("curl", "http://..."), stdout=subprocess.PIPE)
答案 1 :(得分:1)
您未在命令行中指定URL,因此curl
正在打印错误消息并退出。因此,stdout上没有输出。您尝试在标准输入上发送网址,但curl
无效。
相反,请尝试:
p = subprocess.Popen(["curl", "http://validator.w3.org/check?uri=" + url],
stdout=subprocess.PIPE, shell=False)
或者,你知道,只需使用urllib2
(或requests
)并在原生Python中执行,而不是炮轰curl
并处理所有管道。
答案 2 :(得分:1)
执行命令后,您将数据传递给Popen
。
试试这个:
def validateURL(url):
p = subprocess.Popen(["curl", "http://validator.w3.org/check?uri=" + url + "\n"],
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
shell = False)
stdout_data = p.stdout.read()
print stdout_data
result = re.findall("Error", stdout_data)
print result # empty here
if (len(result) != 0):
return 'ERR'
else:
return 'OK'