python - 如何使用“|” 与 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 无法处理管道('|')。有什么办法可以强制它使用管道?
解决方案
在 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'
推荐阅读
- javascript - 从 php 表单中的 div id 获取字段值
- python-3.x - Portscanner 永远扫描一个网站
- python - 如何获得函数的转换作为返回?
- indexing - couchbase 如何确保 id 的唯一性?
- mongodb - 找不到类型 java.sql.Date。您是否缺少对类路径的依赖?
- php - 点击后如何获取图像ID?
- excel - 如何忽略没有用户输入?
- python - Pandas pivot_table 错误地显示 NaN 值
- ruby-on-rails - 如何使用 react_on_rails 的 Redux API 为商店补充水分?
- python - Matplotlib 中的三色(单色)颜色图