python : os.dup2, works in pycharm but not pyinstaller

129 Views Asked by At
    import os
    import sys
    
    if __name__ == '__main__':
        out_fd = os.open('out.txt', os.O_CREAT | os.O_WRONLY)
        os.dup2(out_fd, sys.stdout.fileno())
        print('test')
        os.close(out_fd)

As you can see, this is a simple python code that sends stdout to a file.

And it works in pycharm.

However, it does not work after creating an exe file with pyinstaller.

> stdout_dup2_test.exe
Traceback (most recent call last):
  File "stdout_dup2_test.py", line 7, in <module>
OSError: [WinError 6] The handle is invalid
[6436] Failed to execute script stdout_dup2_test
Traceback (most recent call last):
  File "<string>", line 1, in <module>
OSError: [WinError 6] The handle is invalid
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
OSError: [WinError 6] The handle is invalid

I tested on python 3.7.9 + pyinstaller 4.0 and python 3.6.9 + pyinstaller 3.6

> pyinstaller stdout_dup2_test.py
0

There are 0 best solutions below