有没有一种方法可以让我从Python执行一个shell程序,它将输出打印到屏幕上,然后将它的输出读入变量而不在屏幕上显示任何内容?在
这听起来有点令人困惑,所以也许我可以用一个例子来解释它。在
假设我有一个程序,它在执行时将某些内容打印到屏幕上
bash> ./my_prog
bash> "Hello World"
当我想在Python中将输出读入变量时,我读到一个好的方法是使用subprocess
模块,如下所示:
有了这个构造,我可以将程序的输出输出输出到my_var
(这里是"Hello World"
),但是当我运行Python脚本时,它也会被打印到屏幕上。有什么办法可以抑制这种情况吗?我在subprocess
文档中找不到任何内容,所以可能还有另一个模块可以用于此目的?在
编辑:
我刚发现commands.getoutput()
让我这么做。但是在subprocess
中是否也有实现类似效果的方法?因为我计划在某个时候做一个Python的版本。在
编辑2:具体例子
摘自python脚本:
oechem_utils_path = "/soft/linux64/openeye/examples/oechem-utilities/"\
"openeye/toolkits/1.7.2.4/redhat-RHEL5-g++4.3-x64/examples/"\
"oechem-utilities/"
rmsd_path = oechem_utils_path + "rmsd"
for file in lMol2:
sReturn = subprocess.check_output("{rmsd_exe} {rmsd_pars}"\
" -in {sIn} -ref {sRef}".format(rmsd_exe=sRmsdExe,\
rmsd_pars=sRmsdPars, sIn=file, sRef=sReference), shell=True)
dRmsds[file] = sReturn
屏幕输出(请注意,不是“所有内容”都打印到屏幕上,而是
输出,如果我使用commands.getoutput
一切正常:
/soft/linux64/openeye/examples/oechem-utilities/openeye/toolkits/1.7.2.4/redhat-RHEL5-g++4.3-x64/examples/oechem-utilities/rmsd: mols in: 1 out: 0
/soft/linux64/openeye/examples/oechem-utilities/openeye/toolkits/1.7.2.4/redhat-RHEL5-g++4.3-x64/examples/oechem-utilities/rmsd: confs in: 1 out: 0
/soft/linux64/openeye/examples/oechem-utilities/openeye/toolkits/1.7.2.4/redhat-RHEL5-g++4.3-x64/examples/oechem-utilities/rmsd - RMSD utility [OEChem 1.7.2]
/soft/linux64/openeye/examples/oechem-utilities/openeye/toolkits/1.7.2.4/redhat-RHEL5-g++4.3-x64/examples/oechem-utilities/rmsd: mols in: 1 out: 0
/soft/linux64/openeye/examples/oechem-utilities/openeye/toolkits/1.7.2.4/redhat-RHEL5-g++4.3-x64/examples/oechem-utilities/rmsd: confs in: 1 out: 0
如果
subprocess.check_ouput
不适合您,请使用Popen对象和PIPE
以Python格式捕获程序的输出。在.communicate()
方法将等待一个程序完成执行,然后返回一个(stdout, stderr)
的元组,这就是为什么要使用[0]
的元组。在如果您还想捕获
stderr
,那么将stderr=subprocess.PIPE
添加到Popen
对象的创建中。在如果您希望在
prog
运行时捕获它的输出而不是等待它完成,可以调用line = prog.stdout.readline()
一次读取一行。请注意,如果没有可用的行,则此操作将挂起,直到有可用的行为止。在为了补充Ryan Haining的答案,您还可以处理stderr以确保屏幕上没有打印任何内容:
我总是使用Subprocess.Popen,这通常不会给您任何输出
相关问题 更多 >
编程相关推荐