0

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?.

5
  • Drop the "2" and it will work. What does the "2" request on windows? Commented Oct 31, 2021 at 7:21
  • It is not working. Commented Oct 31, 2021 at 7:23
  • You will have to be more specific. On Linux -n = Numeric output only, -c count = Stop after sending count packets Commented Oct 31, 2021 at 7:30
  • On a side note: Unless you're using a very old version of 3 then you might want to consider using subprocess.run and its related high-level functions instead of working with Popen directly. Commented Oct 31, 2021 at 7:42
  • Thank you, yes, the flag was the whole problem. On Linux -c and windows -n Commented Oct 31, 2021 at 7:52

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.