Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

python - passing data to subprocess.check_output

I want to invoke a script, piping the contents of a string to its stdin and retrieving its stdout.

I don't want to touch the real filesystem so I can't create real temporary files for it.

using subprocess.check_output I can get whatever the script writes; how can I get the input string into its stdin though?

subprocess.check_output([script_name,"-"],stdin="this is some input")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/subprocess.py", line 537, in check_output
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
  File "/usr/lib/python2.7/subprocess.py", line 672, in __init__
    errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  File "/usr/lib/python2.7/subprocess.py", line 1043, in _get_handles
    p2cread = stdin.fileno()
AttributeError: 'str' object has no attribute 'fileno'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Popen.communicate instead of subprocess.check_output.

from subprocess import Popen, PIPE

p = Popen([script_name, "-"], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate("this is some input")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...