How to redirect standard input/standard output/standard error when replacing a process with os.execl
Consider the following sample script:
import os
import sys
print(1)
os.execl(sys.executable, sys.executable, '-c', 'print(2)')
print(3)
The result is
1
I’m looking forward to it
1
2
I think this is because the replacement process does not use the same standard input/standard output/standard error?
How do I achieve my desired goals when using execl
?
I use Python 3.6 on Windows.
Solution
It’s not a bug about PyCharm because I can’t reproduce it with IDEA either. IDEA uses the same kernel as PyCharm.
This is because of the way you start the script. If you start your script using Run
, it will run. If you start it with Debug,
it won’t.
Because Run
simply runs the script in the terminal, Debug
starts the debugger and connects the process to it. The output you see is actually from the debugger, not directly from your script. When you replace your process, the debugger does not reestablish a connection to the newly created process.
That’s why you don’t get 2
outputs.