【问题标题】:Why is ping failing in subprocess?为什么 ping 在子进程中失败?
【发布时间】:2020-08-04 00:27:53
【问题描述】:

我从subprocess.Popen() 中收到一个错误,因为该命令在命令行上运行良好。

命令很简单:

pax> ping -c2 127.0.0.1
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1:icmp_seq=1 ttl=64 time=0.022 ms
64 bytes from 127.0.0.1:icmp_seq=2 ttl=64 time=0.060 ms

但是,当我尝试从 Python(交互式)执行此操作时,它就像我已经离开了地址:

>>> import shlex
>>> import subprocess
>>> args = shlex.split("ping -c2 127.0.0.1") ; print(args)
['ping', '-c2', '127.0.0.1']
>>> proc = subprocess.Popen(args, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> print(proc.stdout.read()) ; print(proc.stderr.read())
b''
b'ping: usage error: Destination address required\n'

该错误消息正是我尝试执行时得到的:

ping -c2

来自没有地址的外壳。

这可能是什么原因造成的?

【问题讨论】:

  • 为什么在不需要的时候使用标准输入?

标签: python python-3.x subprocess popen


【解决方案1】:
#!/bin/env python

import shlex
import subprocess

args = shlex.split("ping -c2 127.0.0.1")
cmdproc = subprocess.Popen(args, stdout=subprocess.PIPE)
print(cmdproc.stdout.read())

这是你可以做的。删除shell=Truestdin=subprocess.PIPE

然后生成以下内容:

b'PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.\n64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.026 ms\n64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.043 ms\n\n--- 127.0.0.1 ping statistics ---\n2 packets transmitted, 2 received, 0% packet loss, time 999ms\nrtt min/avg/max/mdev = 0.026/0.034/0.043/0.010 ms\n'

进一步解释好像你使用shell=True参数,根据[1]你需要将args指定为字符串,即“ping -c2 127.0.0.1”

由于您不需要从标准输入输入任何内容,因此您不需要标准输入。

[1] - https://docs.python.org/3/library/subprocess.html

【讨论】:

    【解决方案2】:

    shell=True 用于将命令作为字符串传递时

    proc = subprocess.Popen("ping -c2 127.0.0.1", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    

    如果将 args 作为列表传递,那么它必须是 shell=False

    proc = subprocess.Popen(shlex.split("ping -c2 127.0.0.1"), shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    

    来自docs

    如果传递单个字符串,shell 必须为 True(见下文),否则字符串必须简单地命名要执行的程序而不指定任何参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多