【问题标题】:Python subprocess script works on Windows but not on LinuxPython 子进程脚本适用于 Windows 但不适用于 Linux
【发布时间】: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


【解决方案1】:

Windows 上的 Ping 命令类似于 ping -n 2 google.com,但在 linux 上是 ping -c 2 google.com。尝试使用if os.name() == 'posix' for linux 和if os.name() == 'nt' for windows 并编写两个命令,每个操作系统一个。

【讨论】:

    猜你喜欢
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 2020-12-22
    相关资源
    最近更新 更多