我想执行bash命令并获取输出,我决定使用Popen和Communicate来执行此操作。这项工作必须在一个循环中完成。问题是在第一轮循环中,每件事都可以,但在下一个循环中,我在使用通信功能时会出现错误。我知道通信功能只能使用一次,但我在每个循环中创建一个新的子进程,因此应该可以进行通信。 这是代码:
with open('ComSites2.txt') as file:
for site in file:
sf = site.split()
temp = "http://wwww." + sf[0]
command = "wget --spider -S '%s' 2>&1 | grep 'HTTP/' | awk '{print $2}'" %temp
print command
output = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
StatusCode = int(output.communicate()[0])
if StatusCode == 200:
print "page found successfully"
elif StatusCode == 404:
print "Page not found!!"
else:
print "no result got!!"
当我运行这个时,我得到了这个输出:
wget --spider -S 'http://wwww.ACAServices.com' 2>&1 | grep 'HTTP/' | awk '{print $2}'
page found successfully
wget --spider -S 'http://wwww.ACI.com' 2>&1 | grep 'HTTP/' | awk '{print $2}'
Traceback (most recent call last):
File "/root/AghasiTestCases/URLConnector.py", line 17, in <module>
StatusCode = int(output.communicate()[0])
ValueError: invalid literal for int() with base 10: ''