我尝试编写一个包含 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/