Hey. I am reading the book A Byte of Python. There, on the 32nd page http://wombat.org.ua/AByteOfPython/AByteofPythonRussian-2.01.pdf , its own helloworld command is created and with the help of it you can call the file helloworld.py from anywhere. For example, just py / helloworld.py I manage to run, but I don’t understand how to make my team. I know there are alies, but in the book it is somehow done differently. Who can tell me how to repeat the example? And what is different from alies?

  • while you write the code, by the end of the book you will understand everything - do not be distracted by trifles - titov_andrei

3 answers 3

How to run a python file from anywhere in Ubuntu?

Like any other program:

  • the file must be in one of the directories specified in $PATH

     $ echo $PATH 
  • file must be executable

     $ chmod +x путь/к/helloworld.py 
  • The file must contain the correct shebang line at the top, for example:

     #!/usr/bin/env python3 

If the ~/bin directory is in $PATH , then you can create symlink:

 $ ln -s /полный/путь/к/helloworld.py ~/bin/helloworld 

After that, you can run helloworld from any directory:

 $ helloworld 

Alternatively, you can use the setup.py file to automatically create an executable file on the path from helloworld.py :

 from setuptools import setup setup( name='helloworld', version='0.1', py_modules=['helloworld'], entry_points=''' [console_scripts] helloworld=helloworld:main ''', ) 

The code to run should be placed in the main() function.

To install the script (from the directory with setup.py ):

 $ python -m pip install . 

If you are not using virtualenv, then you can add the --user option to put the following for the current user locally:

 $ python -m pip install . --user 

you need to add ~/.local/bin to the path ( $PATH environment variable) in this case.

After that, you can run helloworld from any directory:

 $ helloworld 

And what is the difference of this approach from alies?

It is easier to say what is common: alias (pseudonym) as well as other approaches allows you to type the desired command by typing a line, for example: helloworld . alias is shell functionality (such as bash ). Both symlink and explicit installation using setup.py given in the answer do not require a shell to start the command later, for example, you can run rc = subprocess.call('helloworld') from Python.

  • Comments are not intended for extended discussion; conversation moved to chat . - Nick Volynkin
  • @jfs This link doesn’t exist. - Sokolov.G
 $ chmod a+x helloworld.py 

After that, we can run the program directly, because our operating system will run / usr / bin / env, which, in turn, will find Python 3, which means it will be able to run our file.

 $ ./helloworld.py 

Hello World!

  • Thank. This I just did) - Sokolov.G

You need to add the path to the directory with your script in the PATH environment variable:

 PATH=$PATH:/path/to/your/dir