【问题标题】:Fetching the output of a command executed through os.system() command [duplicate]获取通过 os.system() 命令执行的命令的输出
【发布时间】:2021-11-07 05:52:32
【问题描述】:

我正在使用一个脚本,我使用 os.system() 命令向远程服务器 (ssh) 发出 shell 命令。我需要收集我在远程服务器上执行的命令的输出。问题是双重重定向。我正在使用 os.system() 来执行 ssh 命令,该命令在远程服务器上执行预期的命令。我打算利用这个输出。我只需要一些关于如何实现这一点的指示吗?

【问题讨论】:

  • 问题不在于双重重定向。 ssh 只是直接传递输出,所以额外的重定向不会增加任何新问题。但是os.system 永远不会返回输出,它只是将它传递给stdout,因此无论是否有额外的重定向,您的代码都不起作用。
  • 另外,如果您阅读了os.system 上的文档,它会明确告诉您“subprocess 模块提供了更强大的工具来生成新进程并检索它们的结果; 使用那个模块比使用这个函数更可取。"然后它链接到一个部分,显示如何完全按照您的要求进行操作。

标签: python linux unix ssh os.system


【解决方案1】:

使用subprocess 模块:

subprocess.check_output 将命令的输出作为字符串返回。

>>> import subprocess
>>> print subprocess.check_output.__doc__
Run command with arguments and return its output as a byte string.

    If the exit code was non-zero it raises a CalledProcessError.  The
    CalledProcessError object will have the return code in the returncode
    attribute and output in the output attribute.

【讨论】:

  • +1。它还有一个优点是可以让您将 args 作为列表传递,而不必弄清楚构建ssh 命令行所带来的双重shell引用的混乱,并且不可能忘记检查退出状态,还有……
猜你喜欢
  • 2016-04-22
  • 1970-01-01
  • 2015-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
相关资源
最近更新 更多