python - 在 python 调用 perl 脚本中使用 stdin 而不是文件

标签 python perl python-2.7 subprocess

我正在运行一个 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/

相关文章:

perl - 在 Perl 中使用常量

regex - 为什么即使 $foo 匹配模式, `return $foo if/pattern/;` 也不返回 $foo?

python - 如何解决此错误 : 'product.template' has no attribute 'generate_ean13' ?

python - 将 random.random uniform 转换为指数分布不会产生正确的结果

python - 从 html 表中获取数据并将其发送到 Pyramid 中的 View

在 64 位 Windows 上进行 Python 32 位开发

python-2.7 - XPath 切断 href 属性

python - 在 Django ORM 的单个请求中获取一个相关对象

arrays - 从文件中读取多级哈希并将特定值推送到单独的数组

python - 在python中删除列表中的项目