1

I need to write a simple python (python3) script to store my local Ip address in a variable in order to manipulate it later, I read a lot around but I don't understand where I'm doing wrong here a chunk of code for a better understanding..

#!/usr/bin/env pyhton3
import os
import subprocess
import sys
import fileinput
localip = subprocess.call(["ifconfig | grep 'inet addr' | cut -d ':' -f2 | grep 'Bcast' | cut -d ' ' -f1"], shell=True)
print localip
...
...
...

now when I excecute it it prints me this:

pi@raspberrypi:~/Documents $ python change.py
192.168.1.6
0

It seems I can't find a solution to this on my own, can anyone tell me where I'm doing wrong and help me out? thanks.

2
  • As explained in the documentation, the value returned by subprocess.call is the command's return code, which is used to indicate whether the command succeeded. In this case it is zero, because there was no error. Commented Mar 18, 2016 at 17:00
  • Don't go out to the shell to get info about your network interface. I don't know if this is the canonical solution, but it took all of 10 seconds to find pypi.python.org/pypi/netifaces Commented Mar 18, 2016 at 17:08

2 Answers 2

2

To address your XY Problem, why not just use Python itself to get your IP / hostname?

>>> import socket
>>> socket.gethostname()
'MY-COMPUTER'
>>> socket.gethostbyname(socket.gethostname())
'192.168.1.126'
>>> socket.getfqdn()
'my-computer.local'
>>> socket.gethostbyname(socket.getfqdn())
'192.168.1.126'
Sign up to request clarification or add additional context in comments.

Comments

1

In python2, you'd do:

stdout = subprocess.check_output(args, shell=true)

In python3, you can also do:

completed_process = subprocess.run(args, shell=True)
stdout = completed_process.stdout

Which might be a more useful interface

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.