更糟糕的是子进程,列表

时间:2014-05-08 16:58:01

标签: python list subprocess

我有以下代码

clearfile = '/tmp/jjj'
passphrase = "one fish two fish"

opts = '--no-tty --homedir=/www/vhost/.gnupg --passphrase-fd 0 -a -c -o - '
cmd = ['/usr/bin/gpg', opts, clearfile ]

print opts
print cmd

proc = subprocess.Popen(cmd, stdin=subprocess.PIPE,stdout=subprocess.PIPE)
out,err = proc.communicate(passphrase)
gpgdata = out.read()
out.close()

print gpgdata

我知道读取位错误,但命令失败,因为它截断了opts并且我收到以下错误

gpg: invalid option "--no-tty --homedir=/www/vhost/.gnupg --passphrase-"
Traceback (most recent call last):
  File "./test", line 26, in <module>
    gpgdata = out.read()
AttributeError: 'str' object has no attribute 'read'

为什么opts字符串被截断?

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您应该阅读精细手册:

https://docs.python.org/2.7/library/subprocess.html?highlight=popen#subprocess.Popen

  

subprocess.Popen(args):args应该是一个程序序列   参数或单个字符串。默认情况下,要执行的程序   如果args是序列,则是args中的第一项。如果args是一个字符串,   解释依赖于平台[...] 除非另有说明,否则建议通过   args作为一个序列。

>>> import shlex, subprocess
>>> command_line = raw_input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print args
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!