我有一个保存在文本文件中的IP地址列表,我想使用子进程模块和for循环检查它们的代码编号(404200504…)。对于一个IP地址,我的代码工作正常,但当我尝试一个列表包含多个IP地址时,它会给我一些错误。你知道吗
这是我的文本文件:
77.87.19.114
143.21.15.91
17.63.33.21
24.44.12.181
我使用的代码:
from subprocess import check_output
def ipcheck200(ip_list_file):
with open(ip_list_file) as f:
content = f.readlines()
for item in content:
# url generator for each ip
url = "http://" + item + "/"
#print(content[0])
# command generator for each ip
command = "python -c " + '"'
command += "import urllib ;"
command += "a = urllib.urlopen('%s') ;print(a.getcode())" % url
command += '"'
proc = check_output(command)
print(proc)
结果将是:
> Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
ipcheck200('test.txt')
File "C:\Users\XXXX\XXXX\XXXX\file.py", line 17, in ipcheck200
proc = check_output(command)
File "C:\Python27\lib\subprocess.py", line 573, in check_output
raise CalledProcessError(retcode, cmd, output=output)
CalledProcessError: Command 'python -c "import urllib ;a = urllib.urlopen('http://77.87.19.114
/') ;print(a.getcode())"' returned non-zero exit status 1
当存在未处理的异常时,Python将以
1
退出。你知道吗您没有错误处理;如果IP地址不存在,包含额外的空白,或者即使计算机拒绝连接或只是超时,
urllib.urlopen()
也会引发异常:您的代码从文件中提取行而无需进一步处理;每行至少会附加一个换行符,因此您希望剥离行:
您还正在执行序列中的所有子进程,因为} module :
check_output()
等待进程首先完成;这将比在同一进程中运行此代码慢。不要在这里重新发明多处理轮,而是使用^{此示例将使用10个子进程并行测试ip地址。你知道吗
相关问题 更多 >
编程相关推荐