可以在python脚本中交叉引用bash和python变量吗
当我在python脚本中使用可以在python脚本中交叉引用bash和python变量吗,python,bash,Python,Bash,当我在python脚本中使用os.system运行shell命令时,我可以得到一个值n,但我还需要求和以得到python脚本中后续计算的总数 total=0 for i in xrange(1,8): os.system('n=$(qstat -n1 | grep -o node'+str(i)+' | wc -l) && echo $n') 可能吗?也可以在shell命令中使用python变量,比如 os.system('echo $total') 使用shell
os.system
运行shell命令时,我可以得到一个值n
,但我还需要求和以得到python脚本中后续计算的总数
total=0
for i in xrange(1,8):
os.system('n=$(qstat -n1 | grep -o node'+str(i)+' | wc -l) && echo $n')
可能吗?也可以在shell命令中使用python变量,比如
os.system('echo $total')
使用shell的
export
命令:
$ export ABC=1 # Set and export var in shell
$ bash # Start another shell
$ echo $ABC # variable is still here
1
$ python # Start python still in the deeper shell
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from os import environ # import environnement
>>> environ['ABC'] # And here's the variable again (it's a string because the shell doesn't have types)
'1'
您可以
子流程
模块的检查输出
方法如下
import subprocess
print sum(int(subprocess.check_output(["/bin/sh", "-c", "n=`expr {} + 1` && echo $n".format(i)])) for i in range(10))
输出
55
我给了你你想要的,但我不认为这是最好的处理方式。你可以得到os.system的输出,或者用python完成所有的工作。你到底想解决什么问题?这听起来像是XY问题。很抱歉造成混淆。我只想用Python脚本与shell命令的输入和输出进行通信。子流程API适合我。谢谢你的详细回答!它为我澄清了一些事情,但我希望在Python脚本中使用bash变量。所以子流程是合适的选择。谢谢!它正是我想要的。