我编写了一个简单的脚本来检查子进程模块,并在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上运行有什么不同?
发布于 2021-10-31 07:23:50
windows上的Ping命令类似于ping -n 2 google.com,但在linux中是ping -c 2 google.com。尝试使用适用于linux的if os.name() == 'posix'和适用于windows的if os.name() == 'nt',并编写两个命令,每个命令对应一个操作系统。
https://stackoverflow.com/questions/69784671
复制相似问题