0

I am trying to make a def statement that uses os.system(ping) with a variable, and it does not want to take the variable:

import os

def myping(myip):
    print(myip)
    ip1 = os.system("ping -c 1 myip")
    print(ip1)
myping("127.0.0.1")

This returns a code of 512 (fail, rather than a 0, which is success) and then "ping: unknown host myip". Depending on how I format the myip in the os.system statement I can also get a 256 with another error. I have tried various ways of formatting it, including quotation marks, parentheses, percent signs and such, and I'm just not sure what I'm doing wrong.

I can tell I am making it think I want to scan for myip (literal string). What syntax do I have wrong here? Thanks.

By the way, print(myip) within the def statement does give me 127.0.0.1.

spideyclick
  • 162
  • 1
  • 1
  • 12
  • `ip1 = os.system("ping -c 1 {}".format(myip))` – dano May 14 '14 at 18:05
  • This is so funny. I came back to look at this question 2 years later because it had a couple thousand views, and right away I could see what was wrong. Experience! Thanks for the help, guys! I needed it! – spideyclick Apr 08 '17 at 15:26

2 Answers2

3

You probably want to get the value of myip into the argument to os.system:

ip1 = os.system('ping -c 1 {}'.format(myip))

or (old style, deprecated in python 3.1):

ip1 = os.system("ping -c 1 %s" % myip)
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • You should favor the second approach. `%s` style string interpolation is deprecated in favor of `.format`, as noted in the Python documentation here: https://docs.python.org/2/library/stdtypes.html#str.format – dano May 14 '14 at 18:11
  • On Windows 7 and Python 3.3 the return code is 1 without regard to whether the IP is reachable or not. – user3286261 May 14 '14 at 18:36
  • Thank you so much--that worked! (specifically, the second method.) – spideyclick May 14 '14 at 19:19
0

another option is

ip = os.system(f'ping -c 1 {myip}')
mate00
  • 2,727
  • 5
  • 26
  • 34