1

My python code takes in a text file and outputs the common words. I want to be able to right-click a text a file and be able to "Open with Application: MyCode.py", but I have no clue how.

Do I have to make a .exe? I probably need to import something...

I'm on Linux but Windows answer is also welcome. Thx.

2 Answers 2

2

Did you try to create a .sh file or .bat file that launches your python program with your file as first argument? Then just make .sh executable with chmod +x. and you are good to go.

MYPROGRAM.sh

#!usr/bin/python

import argparse

def MyCode(filename):
    for line in filename.readlines():
        # do something
        pass
    
if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('filename', type=argparse.FileType('r'))
    args = parser.parse_args()
    myCode(args.filename)

Then you can link this executable to open any .txt file or from the terminal as

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

2 Comments

Is there any reason to use this over MYPROGRAM.py and leave out the shebang?
you must call your file with python3 MYPROGRAM.Py, you can't just double click it.
-1

check out pyinstaller, its a library which turns your py file into an exe which you can run by double clicking.

3 Comments

This seems to be the right track, however I am still unsure about how to use the targetfile for input in my program.
while making the exe, you can pass the parameter for the file. However once you've made an exe and lets say it targets temp.txt file for data, you cannot change the target file without remaking the exe.
There is no reason to have the target file be fixed inside your .exe. Once Pyinstaller has created my_program.exe, using it in Windows Explorer to open a file is equivalent to running my_program.exe the_file_you_clicked in the terminal. You can find the_file_you_clicked in sys.argv in Python.

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.