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

标签 python linux bash

我有我的 python 脚本

var1 = subprocess.Popen("pwd | grep 'home' ");
print var1

但它给我错误

最佳答案

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

var1 = subprocess.Popen("pwd | grep 'home' ", shell=True)

(请注意,您不需要在该行的末尾使用分号。)不过,这可能不会达到您的预期 - 它返回一个 Popen 对象,因此您需要检查 var1. wait() 是否返回 0

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

if 'home' in os.getcwd():
    print "'home' is in the current working directory's path"

关于使用子进程时 Popen 出现 python 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5847419/

相关文章:

python - 如何在 CKAN 2.2 中定义自定义验证器

python - 在 Python 中对算法进行排序的最快方法

linux - 让 bash 脚本在另一个 bash 脚本中输出一个字符串

python - 从 BeautifulSoup 结果中获取表单 "action"

python - 在 Pandas 中减少(折叠)

linux - 多行复制粘贴到 mongo shell

linux - bash 脚本中的 awk 脚本

linux - 从单线程应用程序调用pthread_self()

linux - 解压缩连接两个 gzip 文件的结果是否总是等于以原始和解压缩形式连接两个文件的结果?

linux - 查找包含非打印字符(空字节)的文件