【问题标题】:Why do I get FileNotFoundError when using subprocess.Popen?为什么在使用 subprocess.Popen 时会出现 FileNotFoundError?
【发布时间】:2018-08-17 00:10:36
【问题描述】:

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

我在这里做错了什么?

【问题讨论】:

  • os.system 只返回一个退出代码——如果有效,则返回数字 0,如果出现错误,则返回其他数字。这真的是你想要的吗?如果没有,请按照文档中的说明和use the subprocess module instead
  • 同时,“有这个错误”……什么错误?如果您希望我们对其进行调试,您必须将其展示给我们(并确保粘贴整个回溯)。
  • 我想,我必须使用子进程模块。而不是操作系统。

标签: python bash cmd grep cut


【解决方案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

【讨论】:

  • 谢谢兄弟,它工作正常,但唯一的问题是它很慢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多