【问题标题】:Getting terminal output of a command from python从python获取命令的终端输出
【发布时间】:2013-09-06 09:56:32
【问题描述】:

我尝试编写一个包含 bash 命令的函数。我想将命令的输出分配给我的python中的变量 我的意思是,函数 gitCheck 找到我的 git Repository 的目录并将其分配给 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

【问题讨论】:

    标签: python shell terminal


    【解决方案1】:

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

    在 Unix 上,返回值是进程的退出状态,编码为 为 wait() 指定的格式。

    ...

    子进程模块为生成提供了更强大的工具 新流程并检索其结果;使用该模块是 最好使用这个功能。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-06
      • 2015-06-13
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 2015-12-08
      相关资源
      最近更新 更多