在对 perl 脚本的 python 调用中使用标准输入而不是文件
Using stdin instead of a file in a python call to a perl script
我正在 运行 使用 subprocess.Popen() 接受来自 Python 的文件作为输入的 perl 脚本。我现在需要脚本的输入来接受来自标准输入而不是文件的输入。如果我 运行 来自 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]`
结果总是 returns 为空(我也尝试过使用 pipe.stdin.write(mytext")
和 result=pipe.stdout.read()
)
请让我知道我做错了什么。
/dev/stdin
应该有效(如果它在您的系统上的 shell 中有效):
>>> from subprocess import Popen, PIPE
>>> import sys
>>> p = Popen([sys.executable, '-c', 'print(open("/dev/stdin").read()[::-1])'],
... stdin=PIPE, stdout=PIPE)
>>> p.communicate(b'ab')[0]
'ba\n'
stdin=PIPE
创建一个管道并将其连接到 child 进程的标准输入。从 /dev/stdin
读取等同于从标准输入 (0
fd) 读取,因此 child 从此处的管道读取,如示例所示。
感谢上面@J.F.Sebastian的评论,我设法用回声和管道解决了这个问题。
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]
其中 returns 预期的输出。仍然不确定为什么原来的(发布在问题中)不起作用(使用通信将文本发送到标准输入)
我正在 运行 使用 subprocess.Popen() 接受来自 Python 的文件作为输入的 perl 脚本。我现在需要脚本的输入来接受来自标准输入而不是文件的输入。如果我 运行 来自 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]`
结果总是 returns 为空(我也尝试过使用 pipe.stdin.write(mytext")
和 result=pipe.stdout.read()
)
请让我知道我做错了什么。
/dev/stdin
应该有效(如果它在您的系统上的 shell 中有效):
>>> from subprocess import Popen, PIPE
>>> import sys
>>> p = Popen([sys.executable, '-c', 'print(open("/dev/stdin").read()[::-1])'],
... stdin=PIPE, stdout=PIPE)
>>> p.communicate(b'ab')[0]
'ba\n'
stdin=PIPE
创建一个管道并将其连接到 child 进程的标准输入。从 /dev/stdin
读取等同于从标准输入 (0
fd) 读取,因此 child 从此处的管道读取,如示例所示。
感谢上面@J.F.Sebastian的评论,我设法用回声和管道解决了这个问题。
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]
其中 returns 预期的输出。仍然不确定为什么原来的(发布在问题中)不起作用(使用通信将文本发送到标准输入)