为什么在使用subprocess.Popen时会出现FileNotFoundError?

时间:2018-08-17 00:10:37

标签: python bash cmd grep cut

我尝试从python执行ping进程:

import subprocess

with open('ips') as f:
    line = f.readlines()
for i in line:
results=subprocess.Popen(["ping -c 1" +  i])
print(results) 

由于以下错误而失败:

Traceback (most recent call last):
File "python_test.py", line 9, in <module>
results=subprocess.Popen(["ping -c 1" +  i])
File "/usr/lib/python3.5/subprocess.py", line 676, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.5/subprocess.py", line 1289, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'ping -c 110.11.1.1\n'

我在这里做什么错了?

1 个答案:

答案 0 :(得分:1)

如果要使用Popen方法,则程序名称和参数必须是列表的单独元素,例如:

for i in lines:
    p1 = subprocess.Popen(['ping', '-c 2', i], stdout=subprocess.PIPE)

    # Run the command
    output = p1.communicate()[0]
    print(output)

从官方文档中读取内容,可能是更常用的run方法。

正式文件

https://docs.python.org/3/library/subprocess.html