When I want to run my python applications from commandline (under ubuntu) I have to be in the directory where is the source code app.py and run the application with command
python app.py
How can I make it (how is it conventionally done) to run the application from arbitrary directory with the command: app
? Similarly as you type ls
, mkdir
and other commands?
thank you
Add the directory that the script is in to your path, make it executable, and add a proper shebang line.
In your .bashrc
:
PATH=$PATH:/dir/to/the/script
Executable:
chmod +x myscript.py
At the top of the script, add the shebang line:
#!/usr/bin/env python
Then, from anywhere, you can just do:
myscript.py
(Note that you don't need a .py suffix, it could be called anything, e.g. app
if you have a proper shebang line).
Add a shebang: as the top line of the file: #!/usr/bin/python
or #!/usr/bin/python3
(you can use the python -B
to prevent generation of .pyc
files, which is why I don't use /usr/bin/env
)
Make it executable: You will need to do chmod +x app.py
(optional) Add directory to path, so can call it anywhere: Add a directory with your executable to your $PATH
environment variable. How you do so depends on your shell, but is either export PATH=$PATH:/home/you/some/path/to/myscripts
(e.g. Linux distros which use bash) or setenv PATH $PATH:/home/you/some/path/to/myscripts
(e.g. tcsh like in Mac OS X). You will want to put this, for example, in your .bashrc
or whatever startup script you have, or else you will have to repeat this step every time you log in.
app.py
will need to be in the myscripts
(or whatever you name it) folder. You don't even need to call it app.py
, but you can just rename it app
.
If you wish to skip step #3, you can still do ./app
to run it if you are in the same directory.
Probably you want to symlink to your file location instead of adding another location to the path
chmod +x app.py
ln ~app.py /opt/local/bin/app
...assuming that /opt/local/bin is already in your path,.
Also, do not forget to add the shebang line to the first line of your script:
#!/usr/bin/env python
A solution some what different from the ones mentioned here: Use an alias.
alias app='python /path/to/app.py'
Add the above line to your ~/.bashrc
or ~/.bash_login
file (or preferably to ~/.bash_aliases
if you are on Ubuntu). Then you can simply use your script as a command line tool with app
.
No need to add a shebang (thereby modifying your existing Python script), no need to make the script executable and no need to change your PATH
.
I'm pretty sure you have to make the script executable via chmod +x
and put it in the PATH variable of your system.