Python Can';似乎无法从subprocess.Popen获取正确的返回值
在bash中,我正在测试驱动器是否像这样安装Python Can';似乎无法从subprocess.Popen获取正确的返回值,python,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
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中
我不知道怎么回事,知道吗?改用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"
感谢您提供的信息,我不知道Popen Being始终为True。
wait()
不运行该命令,而是等待它完成。当您调用Popen构造函数时,该过程确实会启动。这就解释了为什么dmcc建议使用p.wait()编写代码,将Popen更改为call会起到作用,谢谢