3
    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
BonoBono
  • 31
  • 1
  • OS is Windows 10 (1909) – BonoBono Oct 06 '20 at 06:04
  • Could you write to stdout? Try to write it and check. try to write to out_fd and check. I suspect the problem it is on how you create the file (so pyinstaller configuration). – Giacomo Catenazzi Oct 06 '20 at 07:07
  • Hi~ Giacomo Catenazzi. Thanks for comment. It seems to write well in PyCharm. `os.write(out_fd, b'1\n')` `os.dup2(out_fd, sys.stdout.fileno())` `os.write(sys.stdout.fileno(), b'2\n')` – BonoBono Oct 06 '20 at 07:23
  • PyCharm execute program as it should: with stdout/stdin. But when you built for windows, you may choose to have a native windows program, so without console. – Giacomo Catenazzi Oct 06 '20 at 07:40
  • The exe file I made with pyinstaller was executed in "cmd.exe" as a console program. When `os.dup2(out_fd, sys.stdout.fileno())` is commented out, `print('test')` and `os.write(sys.stdout.fileno(), b'2\n'` are displayed on the console screen. – BonoBono Oct 06 '20 at 08:02
  • It depends on how you create the `exe` file, not on how you execute it. You have many options to create an `exe`. Check them. – Giacomo Catenazzi Oct 06 '20 at 08:50
  • It looks like it's an encoding issue: https://github.com/chriskiehl/Gooey/issues/520 – Lorem Ipsum Jun 22 '21 at 14:28

0 Answers0