获取通过 os.system() 命令执行的命令的输出 [英] Fetching the output of a command executed through os.system() command

查看:76
本文介绍了获取通过 os.system() 命令执行的命令的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

使用subprocess 模块:

subprocess.check_output以字符串形式返回命令的输出.

<预><代码>>>>导入子流程>>>打印 subprocess.check_output.__doc__运行带参数的命令并将其输出作为字节字符串返回.如果退出代码非零,则会引发 CalledProcessError.这CalledProcessError 对象将在返回码中包含返回码属性和输出属性中的输出.

I am using a script where I issue a shell command to a remote server (ssh) using os.system() command. I need to collect the output of the command I executed on the remote server. The problem is the double redirection. I am using the os.system() to execute a ssh command which executes the intended command on a remote server. It is this output I intend to make use of. I just need some pointers as to how this can be achieved ?

解决方案

Use the subprocess module:

subprocess.check_output returns the output of a command as a string.

>>> 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.

这篇关于获取通过 os.system() 命令执行的命令的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆