具体来说,universal_newlines=True
参数会在以下情况下进行处理:
- 标准输入(stdin):如果你向子进程发送文本数据,Python 会将其编码为字节流并传递给子进程的标准输入。子进程会将这些字节流解码为文本。
- 标准输出(stdout)和标准错误(stderr):子进程的输出会被解码为文本,而不是字节流。这样在 Python 中可以更方便地处理输出的文本数据。
总的来说,universal_newlines=True
的作用是在 Python 中使用文本模式处理标准输入、输出和错误流,使得处理文本数据更加方便。
下面是一个示例代码,演示了如何使用 universal_newlines=True
参数来启用文本模式处理:
import subprocess
with open(fileName, "w") as logfile:
proc1 = subprocess.Popen(
["./test"],
cwd=testPath,
stdin=subprocess.PIPE,
stdout=logfile,
stderr=subprocess.PIPE,
bufsize=1, # 行缓冲模式
universal_newlines=True # 使用文本模式
)
# 发送 SIGINT 信号给 proc1, 相当于Ctrl + C
proc1.send_signal(signal.SIGINT) # proc1.poll() 值 None
print(proc1.pid)
# 关闭接收数据的程序。 直接终止子进程,可能导致子进程无法完成清理工作。
if proc1.poll() is None:
proc1.terminate()
在Python的subprocess.Popen
中,可以通过将bufsize
参数设置为0来选择无缓冲的I/O。这意味着输入和输出都将被立即处理,而不会被缓冲。
以下是一个简单的示例,演示如何使用bufsize=0
来执行子进程:
import subprocess
执行命令并将输出重定向到文件中
with open(“output.log”, “w”) as logfile:
proc = subprocess.Popen(
[“echo”, “Hello, World!”],
stdout