python - Python 2.x 和 Python 3.x 的脚本不兼容

标签 python python-3.x subprocess

我无法理解 python3 会发生什么,导致它无法工作,当我尝试使用 python3 时,它只是卡在第 11 行。

import io,re,unittest,os,json,sys
from subprocess import PIPE, STDOUT, Popen
sub = Popen(["/usr/bin/python3.4", "test2.py", "pipe"], stdin=PIPE, stdout=PIPE, stderr=sys.stderr, close_fds=True, shell=False)
(writer,reader) = (sub.stdin, sub.stdout)
writer.write("HELO\t1\n".encode("utf-8"))
writer.flush()
sub.poll()
line = reader.readline().decode("utf-8")
assert(re.match("^OK\t", line))
writer.write("Q\ttest.com\tIN\tSOA\t-1\t127.0.0.1\n".encode("utf-8"))
line = reader.readline().decode("utf-8")
assert(re.match("^DATA\ttest.com\tIN\tSOA\t300\t-1\tsns.dns.icann.org. noc.dns.icann.org. 2013073082 7200 3600 1209600 3600", line))
sub.stdout.close()
sub.stdin.close()
sub.kill()
sub.wait()

这是上面代码调用的 test2.py 文件:

import sys
sys.stderr.write(sys.stdin.readline())
sys.stdout.write("OK\tversion foo bar hello\n")
sys.stdout.flush()
sys.stderr.write(sys.stdin.readline())
sys.stdout.write("DATA\ttest.com\tIN\tSOA\t300\t-1\tsns.dns.icann.org. noc.dns.icann.org. 2013073082 7200 3600 1209600 3600")
sys.stdout.flush()

最佳答案

在我的系统上,我重现了您的问题,并通过在第二次 writer.write() 调用后添加 writer.flush() 来修复它。例如:

import io,re,unittest,os,json,sys
from subprocess import PIPE, STDOUT, Popen
sub = Popen(["/usr/bin/python3.4", "test2.py", "pipe"], stdin=PIPE, stdout=PIPE, stderr=sys.stderr, close_fds=True, shell=False)
(writer,reader) = (sub.stdin, sub.stdout)
writer.write("HELO\t1\n".encode("utf-8"))
writer.flush()
sub.poll()
line = reader.readline().decode("utf-8")
assert(re.match("^OK\t", line))
writer.write("Q\ttest.com\tIN\tSOA\t-1\t127.0.0.1\n".encode("utf-8"))
writer.flush() # <<< INSERTED FLUSH <<<
line = reader.readline().decode("utf-8")
assert(re.match("^DATA\ttest.com\tIN\tSOA\t300\t-1\tsns.dns.icann.org. noc.dns.icann.org. 2013073082 7200 3600 1209600 3600", line))
sub.stdout.close()
sub.stdin.close()
sub.kill()
sub.wait()
sub.wait()

如果主脚本在 Python 2 或 Python 3 中运行(测试:2.7 和 3.4),它现在可以正确执行

我说“在我的系统上”是因为这种跨文本管道的交错读写器协调本质上是脆弱的。当它发挥出色时,那就太棒了!但是系统、系统库、语言实现等处理 I/O 的方式的微小变化可能会给您带来各种痛苦。

关于python - Python 2.x 和 Python 3.x 的脚本不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26916610/

相关文章:

python - 属性错误 : 'ModuleSpec' object has no attribute 'load_data_wrapper'

python - 在 Python3 中使用 `random.shuffle` 作为关键字参数时 `random.random` 的运行时间更短

python - 将列表元素与字典的值进行匹配

python - 如何等待所有进程结束

python - 重定向子进程标准输出

python - 使用 subplot2grid 时如何共享

python - 在另一个数组中查找与沿轴的最小值对应的数组

java - 从java导入django模块

python - 在 Python 中设置字典值,同时从最大允许总值中减去

python - 启动另一个程序并在脚本结束时保持运行