我们可以在python代码中使用一个包含linux命令结果的变量吗



我正在使用shell脚本并尝试学习Python脚本,欢迎任何建议。

我想实现以下目标:

用法1:

ps_result=`ps -eaf|grep -v "grep" | grep "programmanager"`

那么我们可以直接在python代码中使用ps_result变量吗;如果是,如何?

用法2:

matched_line=`cat file_name |grep "some string"`

我们可以在python代码中使用matched_line变量作为列表吗?如果可以,如何使用?

PS:如果可能的话,假设我在一个文件中编写bash和python代码,如果不可能,请您提出建议。TIA-

是的,您可以通过环境变量来实现。

首先,使用export:定义shell的环境变量

$ export ps_result=`ps -eaf|grep -v "grep" | grep "programmanager"`

然后,在Python中导入os模块,并读取环境变量:

$ python -c 'import os; ps_result=os.environ.get("ps_result"); print(ps_result)'

第二个问题首先,如果运行python -,python将运行stdin上的管道脚本。pythonsubprocess中有几个函数可以让您运行其他程序。所以你可以写

test.sh

#!/bin/sh
python - << endofprogram
import subprocess as subp
result = subp.run('ps -eaf | grep -v "grep" | grep "python"',
shell=True, capture_output=True)
if result.returncode == 0:
matched_lines = result.stdout.decode().split("n")
print(matched_lines)
endofprogram

在本例中,我们通过shell进行管道传输,但python也可以链接stdout/stdin,尽管更为冗长。

最新更新