【发布时间】: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