noibe
noibe

Reputation: 347

How to Launch a Script from Any Directory with Python

Currently, in order to launch all my python scripts from the terminal I have to go to the relative folder and use

$ python myscript.py

to launch the script. How can I make it so that I can just type

$ myscript

to launch that script, no matter what folder I'm currently in?

Upvotes: 2

Views: 6485

Answers (2)

Gerardo Zinno
Gerardo Zinno

Reputation: 1712

Assuming you are using linux/macos

  1. add this shebang at the beginning of the script #!/usr/bin/env python3
  2. make sure you can execute the file by calling chmod +x myscript.py

Now if you are in the same directory of the script you can run it simply with the command ./myscript.py.

To be able to run the script, no matter what directory you are in:

  1. move the script into a directory listed inside the $PATH environment variable, like /usr/local/bin, or make a directory ad-hoc for your scripts and add that dir to the PATH variable

You can now call your script by just typing its name in the terminal.

Upvotes: 3

Umesh
Umesh

Reputation: 971

You can use alias in your bash_profile for mac or bashrc in linux.

.bash_profile

alias myscript="python /<dir_where_file_is_located>/myscript.py"

once alias is added then reload it

source ~/.bash_profile

Now you can by just type myscript and enter.

$ myscript

Upvotes: 2

Related Questions