1

I want to write the ip address of my system into a file. If i run the following command in my terminal:

ifconfig eth0 grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' awk '{print $1,$2,$3,$4,$5} 
NR==2{exit}' > ip_config.txt

It creates a file called ip_config.txt with the following content

192.168.2.10
255.255.255.0

Now I want to run this command from my python script using os.system(). However if I run

os.system("ifconfig eth0 grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' awk '{print 
$1,$2,$3,$4,$5} NR==2{exit}' > ip_config.txt")

it will create the file but the file is empty. It seems like os.system can't handle the pipe ('|'). Any way I can force it to use the pipe?

Kaiser
  • 15
  • 1
  • 5
  • see this. https://stackoverflow.com/questions/7323859/python-how-to-call-bash-commands-with-pipe – Farhood ET Dec 15 '20 at 13:31
  • Does this answer your question? [Python - How to call bash commands with pipe?](https://stackoverflow.com/questions/7323859/python-how-to-call-bash-commands-with-pipe) – Tomerikoo Dec 15 '20 at 13:47

3 Answers3

4

Subprocess module is your friend when it comes to running shell commands in Python because of it's flexibility and extended support. You can always refer the answer by @BarT.

But if you still insist on writing something using the os module, you can very well use the popen object. Example snippet below (regex and filters according to my machine):

Shell:

$ ifconfig eth0 | grep "inet"
    inet 10.60.4.240  netmask 255.255.248.0  broadcast 10.60.7.255 

Python:

>>> import os
>>> f = os.popen('ifconfig eth0 | grep "inet" | awk \'{print $2}\'')
>>> my_ip=f.read()
>>> my_ip
'10.60.4.240\n'
jagatjyoti
  • 699
  • 3
  • 10
  • 29
1

in general you can't, what you can do is to create a Popen object with stdout=PIPE then you can use communicate().

for more information read the subprocess module, specifically the create a Popen object with stdout=PIPE.

For example:


first_command = subprocess.Popen( ['ifconfig eth0'], stdout=subprocess.PIPE )
stdout, _ = first_command.communicate()
Now stdout will hold the output from running `ifconfig eth0`.
BarT
  • 317
  • 2
  • 10
0

you can also try and avoid the pipe as in this answer by UnknwTech

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])
s.close()
julian
  • 451
  • 2
  • 8