Hi everyone,
Just started programming in Python and iI'm already starting to like this language very much.
I have a problem with a program I wrote last night - I'm trying to ping a certain host using

os.popen("ping xxx.xxx.xxx.xxx"

and then read the %errorlevel% from my system using

result = os.popen("echo %errorlevel%)
print result.read(

the problem is, I keep getting the number zero every time I check for the result data.
usually, getting this value from the %errorlevel%" means that the last command ran without any issues - which means the ping succeeded, but in this case I keep getting 0 even if I ping imaginary hosts.

I think the problem resides in the os.popen use - when I use it the first time it finishes and then closes the command prompt window - so when I check the %errorlevel% variable at the second os.popen command, it gives me the data of a totally new command prompt window!

so my question is - how do I run the first ping command and keep the windows open and run the second "echo %errorlevel% command in the same window?
thanks for reading this long scroll - and thank u very much if you can help :-)

8 Years
Discussion Span
Last Post by Ene Uran

Perhaps you should state why you want to go around pinging sites. os.popen() is probably not the right tool but that depends on what you are trying to do.


Give module subprocess a try, it's a bit more advanced:

import subprocess

# execute the code and pipe the result to a string
test = "ping xxx.xxx.xxx.xxx"
process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE)
# give it time to respond
# optional check (0 --> success)
print process.returncode  
# read the result to a string
result_str = process.stdout.read()
# test it ...
print result_str
This question has already been answered. Start a new discussion instead.
Take the time to help us to help you. Please be thoughtful and detailed and be sure to adhere to our posting rules.