ConorFair
ConorFair

Reputation: 33

How to use Python to "Open Application With:"

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.

Upvotes: 1

Views: 59

Answers (2)

SystemSigma_
SystemSigma_

Reputation: 1435

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

Upvotes: 2

Muhammad Ahmed
Muhammad Ahmed

Reputation: 400

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

Upvotes: -1

Related Questions