Python子进程和bash sed让步:/ bin / sh:2:语法错误:未终止的带引号的字符串

时间:2015-01-02 17:36:32

标签: python bash

#!/usr/bin/python
import subprocess
import pip
installed_packages = pip.get_installed_distributions()
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
    for i in installed_packages])
comms=''.join(installed_packages_list)
filter="sed 's/\,/\n/g' | tr -d '[] ' | sed 's/\x27//g'"
p = subprocess.Popen([filter], stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
vtime = p.stdin.write(comms)
print(vtime)

我正在努力制作并编写一个二进制文件,我可以运行它来生成已安装的Python模块版本的格式化列表。以下产生了令人困惑的输出:

None

bin/sh: 2: Syntax error: Unterminated quoted string

1 个答案:

答案 0 :(得分:0)

您的问题是\ x27是单引号字符,由python解释器解释,导致提前终止您的单引号字符串。尝试添加额外的转义,例如:

filter="sed 's/\,/\n/g' | tr -d '[] ' | sed 's/\\\'//g'"