【发布时间】:2021-10-31 07:16:35
【问题描述】:
我编写了一个简单的脚本来检查子进程模块,并在 Windows 和 Linux 上进行了测试。
该脚本在 Windows 上运行良好,但在 Linux 上却不行。
使用的 Python 解释器都是版本 3。
import subprocess
host = input("Enter a host to ping: ")
p1 = subprocess.Popen(["ping", "-n", "2", host], shell=True, universal_newlines=True, stdout=subprocess.PIPE)
output = p1.communicate()[0]
print(output)
Windows 上的输出:
Enter a host to ping: google.com
Pinging google.com [142.250.183.238] with 32 bytes of data:
Reply from 142.250.183.238: bytes=32 time=17ms TTL=120
Reply from 142.250.183.238: bytes=32 time=16ms TTL=120
Ping statistics for 142.250.183.238:
Packets: Sent = 2, Received = 2, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 16ms, Maximum = 17ms, Average = 16ms
在 Linux 上:
Enter a host to ping: google.com
ping: usage error: Destination address required
在 Linux 上运行有什么区别?
【问题讨论】:
-
去掉“2”就可以了。 windows上的“2”请求什么?
-
它不工作。
-
您必须更具体。在 Linux 上 -n = 仅数字输出,-c count = 发送计数数据包后停止
-
附带说明:除非您使用的是非常旧的 3 版本,否则您可能需要考虑使用
subprocess.run及其相关的高级函数,而不是直接使用Popen。 -
谢谢,是的,标志是整个问题。在 Linux 上 -c 和 windows -n
标签: python python-3.x linux windows