Question

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.

Was it helpful?

Solution

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)

OTHER TIPS

another option is

ip = os.system(f'ping -c 1 {myip}')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top