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

Why do I get FileNotFoundError when using subprocess.Popen?

我尝试从 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'

我做错了什么?

如果你想使用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