-1

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.

leppie
  • 115,091
  • 17
  • 196
  • 297
bvb
  • 633
  • 2
  • 7
  • 15
  • is `localhost` working?And whats the error? – Arvind Apr 05 '14 at 07:55
  • Yeah localhost is working.,error is "ping unknown host" @Arvind – bvb Apr 05 '14 at 08:06
  • You seem to be expecting shell interpretation. That's not something `ping` knows how to do; that's something `bash` or whatever shell you use does. There's a `shell` argument to pass the command through the shell, but it's a crutch. It's safer to get the effects other ways. – user2357112 Apr 05 '14 at 08:24

2 Answers2

0

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.

Ori Seri
  • 917
  • 1
  • 6
  • 14
  • Can you please explain me why you have given cmd ,/c in subprocess.call() @Ori Seri – bvb Apr 05 '14 at 08:13
  • As I said, '>>' is a special character of cmd. Ping doesn't know this sign, it refers it as part of the host you want to ping and tries to resolve it. So, I've opened cmd process instead ping process. The /c argument says to cmd to run the following command and exit (in our case - ping). Cmd refers to the '>>' as redirection and therefore, redirect ping's stdout to a file. Pay attention: cmd process is responsible to redirect the output, not ping process. – Ori Seri Apr 05 '14 at 08:36
  • Iam getting error OSError(Errno 2):No such file or directory when I have given subprocess.call() as above mentioned-@Ori Seri – bvb Apr 08 '14 at 08:15
  • Do you mean: `call(['cmd', '/c', "ping 127.0.0.1 >> out15.txt"])` (or [`call('ping 127.0.0.1 >> out15.txt', shell=True)`](http://stackoverflow.com/a/23067071/4279))? – jfs Apr 14 '14 at 18:13
0

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)

See Multiple ping script in Python.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670