首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python子进程脚本可在Windows上运行,但不能在Linux上运行

问Python子进程脚本可在Windows上运行,但不能在Linux上运行
EN

Stack Overflow用户
提问于 2021-10-31 07:16:36
回答 1查看 63关注 0票数 0

我编写了一个简单的脚本来检查子进程模块,并在Windows和Linux上对其进行了测试。

该脚本在Windows上运行良好,但在Linux上运行不佳。

在这两个平台上使用的Python解释器都是版本3。

代码语言:javascript
复制
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上的输出:

代码语言:javascript
复制
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上:

代码语言:javascript
复制
Enter a host to ping: google.com
ping: usage error: Destination address required

在Linux上运行有什么不同?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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',并编写两个命令,每个命令对应一个操作系统。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69784671

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档