Home > database >  Python subprocess script works on Windows but not on Linux
Python subprocess script works on Windows but not on Linux

Time:10-31

I write a simple script to check the subprocess module and I tested it on both Windows and Linux.

The script works fine on Windows but not on Linux.

The Python interpreter used is version 3 on both.

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)

Output on 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

On Linux:

Enter a host to ping: google.com
ping: usage error: Destination address required

What is the difference when running on Linux?.

CodePudding user response:

Ping command on windows is like ping -n 2 google.com but in linux is ping -c 2 google.com. Try using if os.name() == 'posix' for linux & if os.name() == 'nt' for windows and write two commands, one for each OS.

  • Related