似乎无法从subprocess.Popen获取正确的返回值

时间:2014-10-25 14:37:54

标签: python

在bash中,我正在测试是否像这样安装了一个驱动器

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

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

DriveMounted = "grep -qs \"linuxLUN01\" /proc/mounts"

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

每次运行它时,无论驱动器是否真正安装,我都会显示“已安装驱动器”,即字符串“linuxLUN01”出现在/ proc / mounts中。

我无法弄清楚什么是错的,任何想法?

2 个答案:

答案 0 :(得分: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()的简单便利功能。

答案 1 :(得分:0)

sub.Popen(DriveMounted, shell=True)构造一个始终为Popen的{​​{1}}对象 - 这实际上并不运行该命令。你可能想要更像这样的东西:

True