在Python中执行shell程序而不打印到屏幕

2024-10-01 13:33:27 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以让我从Python执行一个shell程序,它将输出打印到屏幕上,然后将它的输出读入变量而不在屏幕上显示任何内容?在

这听起来有点令人困惑,所以也许我可以用一个例子来解释它。在

假设我有一个程序,它在执行时将某些内容打印到屏幕上

bash> ./my_prog
bash> "Hello World"

当我想在Python中将输出读入变量时,我读到一个好的方法是使用subprocess模块,如下所示:

^{pr2}$

有了这个构造,我可以将程序的输出输出输出到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

Tags: in内容屏幕examplessoftsubprocessutilitiestoolkits
3条回答

如果subprocess.check_ouput不适合您,请使用Popen对象和PIPE以Python格式捕获程序的输出。在

prog = subprocess.Popen('./myprog', shell=True, stdout=subprocess.PIPE)
output = prog.communicate()[0]

.communicate()方法将等待一个程序完成执行,然后返回一个(stdout, stderr)的元组,这就是为什么要使用[0]的元组。在

如果您还想捕获stderr,那么将stderr=subprocess.PIPE添加到Popen对象的创建中。在

如果您希望在prog运行时捕获它的输出而不是等待它完成,可以调用line = prog.stdout.readline()一次读取一行。请注意,如果没有可用的行,则此操作将挂起,直到有可用的行为止。在

为了补充Ryan Haining的答案,您还可以处理stderr以确保屏幕上没有打印任何内容:

 p = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, close_fds=True)
out,err = p.communicate()

我总是使用Subprocess.Popen,这通常不会给您任何输出

相关问题 更多 >