我正在运行一个 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]`
结果总是返回空(我也尝试过使用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]
这会返回预期的输出。仍然不确定为什么原始(发布在问题中)不起作用(使用通信将文本发送到标准输入)
关于python - 在 python 调用 perl 脚本中使用 stdin 而不是文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36446240/