简体   繁体   English

是否可以在python脚本中交叉引用bash和python变量

[英]Is it possible to cross reference bash and python variables in python script

I can get a value n when I run a shell command using os.system in the python script, but I also need to sum it up to get a total number for subsequent computation in the python script, 当我在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')

Is it possible? 可能吗? Also is it possible to use python variable in shell command, something like 也可以在shell命令中使用python变量,例如

os.system('echo $total')

Use the shell's export command: 使用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'

You can subprocess module's check_output method like this 您可以像这样subprocess模块的check_output方法

import subprocess
print sum(int(subprocess.check_output(["/bin/sh", "-c", "n=`expr {} + 1` && echo $n".format(i)])) for i in range(10))

Output 产量

55

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM