-1

I found the answer
So it looks like PyInstaller actually runs in a temp directory, not your own, which explains my issue. This is an explanation for that. I guess I will keep this up incase people in the future have problems.


Original question

I am trying to use PyInstaller to create an executable of a simple python script called test.py that just creates a text file and adds numbers to it, as a test of PyInstaller. This file works correctly when run normally.

from os.path import dirname, abspath

def main():
    txtfile = dirname(abspath(__file__)) + '/text.txt'
    with open(txtfile, 'w') as f:
        for num in range(101):
            f.write(str(num) + '\n')

if __name__ == '__main__':
    main()
    print('script executed')

When I use: pyinstaller test.py --onefile in the same directory as test.py it successfully creates the dist file with the binary file test inside of it.

when I cd dist and do ./test to execute the file inside dist it successfully prints out main called and script executed but it doesn't actually create the file. So, main is being called and the script is being executed, but the file isn't created at all, and I am quite confused about what I'm doing wrong..I must be getting file paths messed up? But I have specified the exact full path with os.path, so it doesn't make sense to me.

The system exit code is 0, and there are no errors raised when I call ./test

dftag
  • 85
  • 2
  • 8
  • Does this answer your question? [Pyinstaller executable saves files to temp folder](https://stackoverflow.com/questions/70405069/pyinstaller-executable-saves-files-to-temp-folder) – Alexander Oct 17 '22 at 03:39
  • When you find the answer to your question in another stack overflow post, that is a good indication that your question is a duplicate and should probably be removed – Alexander Oct 17 '22 at 03:49
  • There is a subtle difference in my post and their post. To find that post, they would have to know that it does save it to a temp file. But people don't know that, which this post would lead them to that info. – dftag Oct 17 '22 at 05:09

1 Answers1

0

I found this that shows that PyInstaller will save to a temp file. I created this script below to check if the script is being executed directly or via PyInstaller.

import os
import sys

def create_file(path):
    with open(path + '/test.txt', 'w') as f:
        for num in range(101):
            f.write(str(num) + '\n')

def check_using_pyinstaller():
    if getattr(sys, 'frozen', False):
        application_path = os.path.dirname(sys.executable)
        return application_path
    return os.path.dirname(os.path.abspath(__file__))

def main():
    path = check_using_pyinstaller()
    os.chdir(path)
    create_file(path)

if __name__ == '__main__':
    main()

dftag
  • 85
  • 2
  • 8