gpt4 book ai didi

python - 从 python 获取命令的终端输出

转载 作者:太空宇宙 更新时间:2023-11-03 18:49:56 28 4
gpt4 key购买 nike

我尝试编写一个包含 bash 命令的函数。我想将命令的输出分配给 python 中的变量我的意思是,函数 gitCheck 找到我的 git 存储库的目录并将其分配给 gitRep 但它只给了我 0。有谁知道我该怎么做?提前致谢

def gitCheck():
reference_repositories_path="cat $HOME/.git_reference_repositories | sed 's/GIT_REFERENCES_PATH=//'"
gitRep=os.system(reference_repositories_path)
print gitRep

输出应该是/home/gwapps/Desktop/GIT_REFERENCE_REPOSITORIES但它给了我0

最佳答案

您正在获取退出状态。根据 os.system() docs :

On Unix, the return value is the exit status of the process encoded in the format specified for wait().

...

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function.

因此,如果您想检索命令的输出,请使用 subprocess 模块。这里有大量关于 SO 的例子,例如:

关于python - 从 python 获取命令的终端输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18587644/

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