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

11

我正在尝试通过以下命令在远程服务器上使用ssh获取命令的输出。

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

这个命令的输出是14549 0。

为什么输出中会有一个零呢?是否有任何一种方法可以将输出存储在变量或列表中?我已经尝试将输出分配给变量和列表,但在变量中只得到了0。我正在使用Python 2.7.3。


4
如果你正在使用Python 2.7,那么请使用subprocess模块代替os.system - Fred Foo
4个回答

15

这里有很多关于这个话题的好的stackoverflow链接。尝试看看使用Python运行shell命令并捕获输出或者将os.system的输出赋值给一个变量并防止其在屏幕上显示,以上仅为入门。

import subprocess
direct_output = subprocess.check_output('ls', shell=True) #could be anything here.

使用shell=True标志应谨慎:

来自文档: 警告

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

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


嗨,我的输出包含这些字符:b'Fri Nov 27 14:20:49 CET 2020\n'。有 b' 和 \n'。你知道为什么会出现这种情况吗?@paul 如果我使用 os.system,它就不会出现,但我无法将其保存在变量中。 - Shalomi90
@Shalomi11 是的,b表示返回的数据是字节而不是字符。请参阅此处以获取更完整的处理方式:https://docs.python.org/3/howto/unicode.html 。简而言之,需要对字节进行解码才能从中返回字符串(例如 b'abc'.decode('utf8') )。换行符只是底层命令返回输出的方式。请参见 https://dev59.com/nloV5IYBdhLWcg3wTdTN 进行讨论。 - Paul

11

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

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

print out
Tue Oct  3 10:48:10 PDT 2017

1

补充Paul的回答(使用subprocess.check_output):

我稍微改写了它,以便更轻松地处理可能引发错误的命令(例如,在非git目录中调用“git status”将抛出返回码128和CalledProcessError)

这是我的Python 2.7示例:

import subprocess

class MyProcessHandler( object ):
    # *********** constructor
    def __init__( self ):
        # return code saving
        self.retcode = 0

    # ************ modified copy of subprocess.check_output()

    def check_output2( self, *popenargs, **kwargs ):
        # open process and get returns, remember return code
        pipe = subprocess.PIPE
        process = subprocess.Popen( stdout = pipe, stderr = pipe, *popenargs, **kwargs )
        output, unused_err = process.communicate( )
        retcode = process.poll( )
        self.retcode = retcode

        # return standard output or error output
        if retcode == 0:
            return output
        else:
            return unused_err

# call it like this
my_call = "git status"
mph = MyProcessHandler( )
out = mph.check_output2( my_call )
print "process returned code", mph.retcode
print "output:"
print out

-3

如果您在交互式 shell 中调用 os.system(),os.system() 将打印命令的标准输出('14549',即 wc -l 的输出),然后解释器将打印函数调用本身的结果(0,可能是命令的不可靠退出代码)。以下是一个更简单命令的示例:

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system("echo X")
X
0
>>>

4
我感觉这并没有回答问题。 - pythonian29033

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接