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 :-)

Recommended Answers

All 3 Replies

run it using IDLE? and the result printed will stay on screen?

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
process.wait()
# optional check (0 --> success)
print process.returncode  
# read the result to a string
result_str = process.stdout.read()
# test it ...
print result_str
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.