使用子进程时Popen出现python错误

Mah*_*aal 0 python linux bash

我有我的python脚本

var1 = subprocess.Popen("pwd | grep 'home' ");
print var1
Run Code Online (Sandbox Code Playgroud)

但它给了我错误

Mar*_*air 6

shell=True如果希望shell正确解释管道,则需要添加:

var1 = subprocess.Popen("pwd | grep 'home' ", shell=True)
Run Code Online (Sandbox Code Playgroud)

(请注意,您不需要在该行的最后一个分号.)这可能不是你所期望的,但-返回一个对象POPEN是的话,你需要检查是否var1.wait()返回0与否.

一个更简单的方法,如果你只是想知道当前目录是否包含'home',那就是:

if 'home' in os.getcwd():
    print "'home' is in the current working directory's path"
Run Code Online (Sandbox Code Playgroud)