I am developing an API in Unix environment for virtual machines. Most of the modules are developed in python. I have few questions on this.
I have the file extension as abc.py
. I would like to make this as a command. For example , virtman dominfo [vmid]
should be the command syntax. Now I have to give ./virtman.py dominfo [vmid]
to achieve this. And I have first line as #!/usr/bin/python
in the python file. So how can make this as a command?
My echo $PATH looks like '/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin0'
I read a lot of articles but I didn't get the clear picture,so any hints/suggestions would be helpful.
Best Answer
You seem to be mistaken in that
abc.py
would not be a command. If you can execute it, then is, just one with a dot in the name. Execute in the sense that you can do./abc.py
, so the execute bits must be set. If you have to dopython abc.py
than you it is not a command (yet).In general, to make a normal python file
abc.py
executable you should make sure the first line reads:(This assumes you have
/usr/bin/env
as a program, and that will find thepython
command, which might be in/usr/local/bin
. It also assumes that you want to run the defaultpython
(which is normally a link to a particular python version likepython2.7
), you could also usepython3
if that is available as a command).After that do
And then you can run
./abc
. If the current directory is in your path, or if you moveabc
to a directory in your path, you should be able to executeabc
from anywhere.¹There are however disadvantages of renaming and moving the file:
from abc import SomeClass
, as the file is renamedSo instead, what I normally do, is make a new file
/usr/local/bin/abc
that looks like:and have at the bottom of
abc.py
:The directory of
abc.py
needs to be in the PATH python searches for modules, but this way it doesn't have to be changed, and can be used by any program as an import, and started aspython abc.py
.¹ The
mv
is necessary to get rid of the dot in the command name, but not really necessary, you can invoke./abc.py
if you don't rename it.