更多关于子进程和列表的问题

2024-03-27 12:20:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码

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

我知道read位是错误的,但是命令失败了,因为它截断了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字符串被截断?你知道吗

谢谢你的帮助


Tags: nocmdreadwwwoutpassphrasesubprocessprint
1条回答
网友
1楼 · 发布于 2024-03-27 12:20:51

您应该阅读精美手册:

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

subprocess.Popen(args) : args should be a sequence of program arguments or else a single string. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent [ ... ] Unless otherwise stated, it is recommended to pass args as a sequence.

>>> 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!

相关问题 更多 >