似乎无法从中获取正确的返回值子流程.Popen

2024-06-26 08:19:49 发布

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

在bash中,我正在测试驱动器是否安装成这样

if grep -qs "linuxLUN01" /proc/mounts; then
    ...do something...

现在我尝试在Python中做同样的事情

^{pr2}$

每次我运行它,我总是看到“drive is mounted”(驱动器已安装),无论驱动器是否已安装,即字符串“linuxLUN01”出现在/proc/mounts中。在

我不知道怎么了,知道吗?在


Tags: bashifisdriveproc事情dogrep
2条回答

使用subprocess.call()代替:

import subprocess as sub
DriveMounted = "grep -qs \"linuxLUN01\" /proc/mounts"

if sub.call(DriveMounted, shell=True):
    print "drive is mounted"
else:
    print "drive is not mounted"

subprocess.Popen只返回Popen实例,而不是它应该执行的命令的返回值。在

subprocess.call(...)subprocess.Popen(...).wait()的一个简单方便函数。在

sub.Popen(DriveMounted, shell=True)构造一个Popen对象,它将始终是True这实际上并没有运行命令。你可能想要更像这样的东西:

import subprocess as sub
p = sub.Popen(['grep', '-qs', 'linuxLUN01', '/proc/mounts'], stdout=sub.PIPE)
p.wait() # waits for the command to finish running
mounted = bool(p.stdout.read()) # see if grep produced any output
print "drive is", "mounted" if mounted else "not mounted"

相关问题 更多 >