簡體   English   中英

Python 子進程腳本適用於 Windows,但不適用於 Linux

[英]Python subprocess script works on Windows but not on Linux

我編寫了一個簡單的腳本來檢查子進程模塊,並在 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 上運行時有什么區別?

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 並編寫兩個命令,每個操作系統一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM