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
I'm pretty sure you have to make the script executable via
chmod +x
and put it in the PATH variable of your system.Add a shebang: as the top line of the file:
#!/usr/bin/python
or#!/usr/bin/python3
(you can use thepython -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 eitherexport PATH=$PATH:/home/you/some/path/to/myscripts
(e.g. Linux distros which use bash) orsetenv 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 themyscripts
(or whatever you name it) folder. You don't even need to call itapp.py
, but you can just rename itapp
.If you wish to skip step #3, you can still do
./app
to run it if you are in the same directory.Add a shebang line at the beginning of your file:
Make your file executable by calling
in the shell.
Move it to some location included in the
PATH
environment variable and rename it toapp
. Alternatively, add the path of the directory containingapp
to thePATH
environment variable by adding the lineto your
.bash_profile
.Add the directory that the script is in to your path, make it executable, and add a proper shebang line.
In your
.bashrc
:Executable:
At the top of the script, add the shebang line:
Then, from anywhere, you can just do:
(Note that you don't need a .py suffix, it could be called anything, e.g.
app
if you have a proper shebang line).Probably you want to symlink to your file location instead of adding another location to the path
...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.
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 withapp
.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
.