I have given
subprocess.call(['ping', '127.0.0.1', '>>', 'out15.txt'])
statement in python script.
But I am getting unknown host error.
Please let me know why I am getting that error.
I have given
subprocess.call(['ping', '127.0.0.1', '>>', 'out15.txt'])
statement in python script.
But I am getting unknown host error.
Please let me know why I am getting that error.
Cause you pass the >> out15.txt
to the ping as argument.
The >>
is special character of cmd\bash. If you insist to redirect the output to file with the command, instead using python code you can do that like this:
subprocess.call(['cmd', '/c', 'ping', '127.0.0.1', '>>', 'out15.txt'])
The same for bash.
As @Ori Seri pointed out >>
is usually interpreted by a shell:
from subprocess import call
call('ping 127.0.0.1 >> out15.txt', shell=True)
Note: the string argument with shell=True
.
You could do it without the shell:
with open('out15.txt', 'ab', 0) as output_file:
call(["ping", "127.0.0.1"], stdout=output_file)
Note: the list argument with shell=False
(the default).
You don't need to write the output file to interpret the ping
results; you could use the exit status instead:
from subprocess import call, DEVNULL
ip = "127.0.0.1"
rc = call(["ping", '-c', '3', ip], stdout=DEVNULL)
if rc == 0:
print('%s active' % ip)
elif rc == 2:
print('%s no response' % ip)
else:
print('%s error' % ip)