How to make keyword for python script "python filename.py"

Viewed 203

I am trying to create an alias for python filename.py so I can use my_keyword to run my script file.

Example:

python filename.py
python filename.py

Need to convert to

my_keyword

So this will call my file.

Is it possible? If it is possible then How I can achieve this.

3 Answers

If you're using Linux, MacOS, or some other Unix-based environment, rename the file to my_keyword and use a shebang line to make it use the Python interpreter, and make the file executable. Then make sure the file is in a directory that's in your shell PATH.

mv filename.py my_keyword
chmod +x my_keyword

Make sure the first line of the file is:

#!/usr/bin/env python

This tells the shell to run Python and to interpret the contents of the file.

You may want to install the file in /usr/local/bin, or add ~/bin to your PATH, so that you can execute the file without entering the full path.

For macOS X Catalina, you can do so via alias:

  1. Open Terminal
  2. Type ls -la to check whether you have .zshrc
  3. If yes, and assuming the file is at a folder in your Desktop, you can simply type the following, do note that you need to swap your_username and your_folder accordingly.

echo "alias key="python /Users/your_username/Desktop/your_folder/filename.py"" >> ~/.zshrc

  1. source ~/.zshrc

For macOS X before Catalina, replace .zshrc with .bash_profile from the instruction above.

Related