我正在运行一个 perl 脚本,它使用 subprocess.Popen() 接受一个文件作为来自 Python 的输入。我现在需要脚本的输入来接受来自标准输入而不是文件的输入。如果我像这样从 shell 运行 perl 脚本:
perl thescript.perl --in /dev/stdin --other_args other_values
它工作得很好。然而,在 python 中,使用以下命令没有任何反应:
mytext = "hi there"
args = ["perl", "myscript.perl", "--in", "/dev/stdin", "--other_args", other_values]
pipe = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
result = pipe.communicate(input=mytext.encode("utf8"))[0]`
result 总是返回空值(我也试过使用 pipe.stdin.write(mytext") 和 result=pipe.stdout.read())
请让我知道我做错了什么。
请您参考如下方法:
感谢上面@J.F.Sebastian 的评论,我设法用 echo 和管道解决了这个问题。
args = ["perl", "myscript.perl", "--in", "/dev/stdin", "other_args", other_vals]
pipe1 = subprocess.Popen(["echo", mytext], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
pipe2 = subprocess.Popen(args, stdin=pipe1.stdout, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
pipe1.stdout.close()
result = pipe2.communicate()[0]
返回预期的输出。仍然不确定为什么原始(发布在问题中)不起作用(使用通信将文本发送到标准输入)
