我有以下三个
python脚本:
parent1.py
import subprocess,os,sys relpath = os.path.dirname(sys.argv[0]) path = os.path.abspath(relpath) child = subprocess.Popen([os.path.join(path,'child.lisp')],stdout = subprocess.PIPE) sys.stdin = child.stdout inp = sys.stdin.read() print(inp.decode())
parent2.py:
import sys inp = sys.stdin print(inp)
child.py:
print("This text was created in child.py")
如果我用parent1.py调用:
python3 parent1.py
它给了我预期的以下输出:
This text was created with child.py
如果我用parent2.py调用:
python3 child.py | python3 parent2.py
我得到相同的输出.但是在第一个例子中,我得到child.py的输出作为字节,而在第二个例子中我直接得到它作为字符串.为什么是这样?它只是python和bash管道之间的区别还是我还能做些什么来避免这种情况?
当python打开stdin和stdout时,它会检测要使用的编码,并使用
text I/O为你提供unicode字符串.
但是子进程不会(也不能)检测您启动的子进程的编码,因此它将返回字节.您可以使用io.TextIOWrapper()
instance来包装child.stdout管道以提供unicode数据:
sys.stdin = io.TextIOWrapper(child.stdout,encoding='utf8')