首页 > 解决方案 > 如何使用“|” 与 os.system?

问题描述

我想将我的系统的 IP 地址写入一个文件。如果我在终端中运行以下命令:

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

它创建一个名为ip_config.txt的文件,其内容如下

192.168.2.10
255.255.255.0

现在我想使用 os.system() 从我的 python 脚本运行这个命令。但是,如果我跑

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")

它将创建文件,但文件为空。似乎 os.system 无法处理管道('|')。有什么办法可以强制它使用管道?

标签: pythonos.system

解决方案


在 Python 中运行 shell 命令时,子进程模块是您的朋友,因为它具有灵活性和扩展支持。您可以随时参考@BarT 的答案。

但是如果你仍然坚持使用 os 模块写东西,你可以很好地使用 popen 对象。下面的示例片段(根据我的机器的正则表达式和过滤器):

壳:

$ 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'

推荐阅读