Python 如何从exec而不是popen捕获stdout/stderr?
我想创建一个Python程序,它接受另一个Python文件作为参数,执行它并处理stdout/stderr,同时仍将stdout/stderr返回给调用进程。基本上,从最终用户的角度来看,这两者应该是等价的(尽管第一个是做一些用户看不到的额外处理) vs 我见过如何使用popen和pipes实现这一点的示例,但由于其他原因,我无法在子流程中实现这一点;它需要使用相同的解释器,所以我需要使用exec。还有可能这样做吗?更清楚地说,我希望passthrough.py的行为如下:Python 如何从exec而不是popen捕获stdout/stderr?,python,Python,我想创建一个Python程序,它接受另一个Python文件作为参数,执行它并处理stdout/stderr,同时仍将stdout/stderr返回给调用进程。基本上,从最终用户的角度来看,这两者应该是等价的(尽管第一个是做一些用户看不到的额外处理) vs 我见过如何使用popen和pipes实现这一点的示例,但由于其他原因,我无法在子流程中实现这一点;它需要使用相同的解释器,所以我需要使用exec。还有可能这样做吗?更清楚地说,我希望passthrough.py的行为如下: def proces
def process_output(text):
pass
def process_err(text):
pass
file_to_run = sys.argv[1]
sys.stdout = sys.stdout && process_output # pipe stdout to sys.stdout AND some func
sys.stderr = sys.stderr && process_err # pipe stderr to sys.stdout AND some func
execfile(file_to_run) # Would actually use exec so it works with 3.x as well
在cpython中,
sys.executable
是当前可执行文件的路径。不适用于嵌入式python,但可能适用于您。您可以查看itertools.tee
来分割每个流,将两个子流中的一个子流分配回sys.whatever
,并将另一个子流传递给process\u whatever
。
python some_example.py
def process_output(text):
pass
def process_err(text):
pass
file_to_run = sys.argv[1]
sys.stdout = sys.stdout && process_output # pipe stdout to sys.stdout AND some func
sys.stderr = sys.stderr && process_err # pipe stderr to sys.stdout AND some func
execfile(file_to_run) # Would actually use exec so it works with 3.x as well