如何在python中的变量或列表中存储os.system()输出

Jit*_*itu 8 python ssh python-2.7

我试图通过使用下面的命令在远程服务器上执行ssh来获取命令的输出.

os.system('ssh user@host " ksh .profile; cd dir; find . -type f |wc -l"')
Run Code Online (Sandbox Code Playgroud)

该命令的输出为14549 0

为什么输出中有零?有没有办法将输出存储在变量或列表中?我已经尝试将输出分配给变量和列表,但我在变量中只得到0.我使用的是python 2.7.3.

Pau*_*aul 10

这个上有很多好的SO链接.尝试从Python运行shell命令并捕获输出将os.system 的输出分配给变量,并防止它在屏幕上显示 为启动器.简而言之

import subprocess
direct_output = subprocess.check_output('ls', shell=True) #could be anything here.
Run Code Online (Sandbox Code Playgroud)

应谨慎使用shell = True标志:

来自文档:警告

如果与不受信任的输入结合使用,则使用shell = True调用系统shell可能会带来安全隐患.有关详细信息,请参阅"常用参数"下的警告.

有关更多信息,请参阅:http://docs.python.org/2/library/subprocess.html


小智 10

您可以使用 os.popen().read()

import os
out = os.popen('date').read()

print out
Tue Oct  3 10:48:10 PDT 2017
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

31270 次

最近记录:

8 年,1 月 前