gpt4 book ai didi

python - 在不打印到屏幕的情况下在 Python 中执行 shell 程序

转载 作者:行者123 更新时间:2023-11-28 22:54:18 27 4
gpt4 key购买 nike

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

这听起来有点令人困惑,所以也许我可以通过一个例子更好地解释它。

假设我有一个程序在执行时会在屏幕上打印一些东西

bash> ./my_prog
bash> "Hello World"

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

my_var = subprocess.check_output("./my_prog", shell=True)

通过这种构造,我可以将程序的输出放入 my_var(这里是 "Hello World"),但是当我运行 Python 时它也会打印到屏幕上脚本。有什么办法可以抑制这种情况吗?我在 subprocess 文档中找不到任何内容,所以也许有另一个模块可以用于此目的?

编辑:我刚刚发现 commands.getoutput() 可以让我这样做。但是有没有办法在subprocess中实现类似的效果呢?因为我计划在某个时候制作一个 Python3 版本。


EDIT2:具体例子

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

最佳答案

要添加到 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()

关于python - 在不打印到屏幕的情况下在 Python 中执行 shell 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18214057/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com