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?
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'
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`.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.