2

I am trying to set my Python script as default program to open a file (e.g. open every .txt file with my program when I double click on it). I already tried this:

from sys import argv

# write the arguments to a file for debugging purposes
with open("output.txt", "w+") as f:
    f.write(repr(argv))

I converted the script into a .exe with pyinstaller, otherwise Windows won't let me use it to open files.

In the command prompt, it works: typing main.exe some args indeed yields an output.txt file, with inside it ["C:\...\main.exe", "some", "args"].

I was hoping that by opening a .txt file with this script (in File Explorer > right click on file > open with > more apps > check "always use this app" and selecting the executable), it would be the same as running main.exe C:\...\that_file_that_i_just_clicked.txt in the command prompt, from which I could then use the file path to open it in my program. However, this does not happen. In fact, main.exe never even gets executed (because it doesn't even create a new output.txt).

How can I link a pyinstaller-generated executable to always open a filetype, and how do I then know the path of the opened file in Python?

2
  • 1
    The "open" action for the autogenerated progid should include the "%1" file path, but it won't include the extra %* command-line arguments, if you need that. Your test script relies on the working directory, and offhand I'm not sure what that will be for a PyInstaller executable. It should be the directory of the target file, but try writing "output.txt" in a fully-qualified location that's hard coded in the script, and include the value of os.getcwd(). Commented Jun 18, 2020 at 19:41
  • 1
    @ErykSun Converting everything to absolute file path seems to have fixed it. The opened file path now appears in output.txt. Thanks! (How do I mark your answer as "correct"?) Commented Jun 19, 2020 at 10:06

1 Answer 1

1

The thing that I was doing wrong, was creating output.txt using a relative file path. Since the script was converted into an .exe (which basically wraps the interpreter and the script into a single file), the relative file path stopped working.

Using an absolute file path fixed my issue (as pointed out by Eryk Sun).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.