Home > Enterprise >  Why Popen('ping URL').communicate() works in Windows and doesn't work in Ubuntu?
Why Popen('ping URL').communicate() works in Windows and doesn't work in Ubuntu?

Time:11-18

I try to run the code on Ubuntu, which works in Windows:

import subprocess 

ARGS = ["ping", "google.com"]
process = subprocess.Popen(ARGS, stdout=subprocess.PIPE)

data = process.communicate()
print(data)

When run under Windows, this code prints out tuples of ping packages. But the same code running on Ubuntu just hangs and nothing else!

Can anyone explain to me why?

CodePudding user response:

The default behavior of ping on most platforms is to just send more packets forever. This will look like it "hangs" because your Python code is waiting for the subprocess to finish, but it never will (though eventually you will fill up memory with the buffered output).

You want to add an option to limit the number of packets, something like

result = subprocess.run(
    ['ping', '-c', '4', 'google.com'],
    capture_output=True, check=True, text=True)
data = result.stdout

Notice also the use of subprocess.run() in preference over the lower-level Popen function. Like the documentation already tells you, you don't want to manage the Popen object yourself if you can avoid it.

CodePudding user response:

After testing on Windows, I saw that ping in Windows sent 4 packets and stopped. ping in Ubuntu, on the other hand, sent infinite packets until quitting the program.

The process.communicate() command will wait for end-of-file (EOF) signal, which it gets to in Windows,obviously, but won't get to in Ubuntu. The solution is making ping in Ubuntu terminate. You can limit the number of packets ping sends with the -c flag. Doing ARGS = ["ping", "-c", "4", "google.com"] should get your program to print the results of 4 packets being sent.

  • Related