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

标签 python shell terminal

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

相关文章:

关于 write() 和 truncate() 的 Python 问题

python - 使用 Conda 更新特定模块会删除大量软件包

python - 将文件从 gcs 复制到 boto3 中的 s3

Python:搜索带有 href 和文本内容的 html 文件抓取 <a> 标签

GIT 在特定提交之前获取提交哈希

MySQL:通过 MAC 中的终端进行 SSH 连接

bash - 使用 grep 时如何去掉 “--” 行分隔符

python - 显示大于桌面的 Tkinter 窗口

linux - 模拟按键 Y Shell Linux

python - 奇怪的编码错误,作为可执行文件与 shell 脚本调用时的行为不同