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

2024-05-19 01:40:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个小代码:

import os
os.system('users')
os.system('w')

这个指纹

ubuntu
 09:27:25 up 9 days, 21:23,  1 user,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
ubuntu   pts/0    42.99.164.66     09:06    5.00s  0.10s  0.00s sh -c w

但当我尝试:

import os
from pyslack import SlackClient

user_name = os.system('users')
login_details = os.system('w')

print user_name
print login_details

它具有以下输出:

ubuntu
 09:28:32 up 9 days, 21:24,  1 user,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
ubuntu   pts/0    42.99.164.66     09:06    0.00s  0.11s  0.00s w
0
0

现在我不确定为什么我不能将结果存储在变量中,即为什么它要打印0?而正确的方法应该是什么呢?


Tags: fromimportosubuntuloginloaddayssystem
3条回答

os.system返回命令的退出代码。

要捕获命令的输出,可以使用subprocess.check_output

output = subprocess.check_output('users', shell=True)

os.system返回的值与您启动的命令的返回值相同。由于大多数调用(如“users”)都是用C编写的,所以当代码成功执行时,它们返回0(它们在main()末尾有一个return 0;)。

如果要保存其输出,可以将其输出路径(默认情况下为stdout)重定向到文本文件,然后读取文本文件。

user_name = os.system('users > users.txt')
login_details = os.system('w > w.txt')

with open("users.txt", "r") as f:
    for line in f:
        print line
with open("w.txt", "r") as f:
    for line in f:
        print line

os.system("rm users.txt")
os.system("rm w.txt")

我向subprocess.check_output溶液鞠躬

os.system(command)开始。

os.system只需在子shell中执行命令(字符串)。

USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
ubuntu   pts/0    42.99.164.66     09:06    5.00s  0.10s  0.00s sh -c w

这意味着上述数据是通过调用标准C函数system()而不是返回值写入标准输出的。

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

On Windows, the return value is that returned by the system shell after running command, given by the Windows environment variable COMSPEC: on command.com systems (Windows 95, 98 and ME) this is always 0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit status of the command run; on systems using a non-native shell, consult your shell documentation.

所以如果退出状态是成功,user_namelogin_details将得到一个零。

事实上,你可以试试这个:

import subprocess
user = subprocess.check_output(['users'])
details = subprocess.check_output(['w'])

print(user)
print(details)

相关问题 更多 >

    热门问题