Search code examples
pythoncommand-line

How do I make a python script executable?


How can I run a python script with my own command line name like myscript without having to do python myscript.py in the terminal?


See also: Why do I get non-Python errors like "./xx.py: line 1: import: command not found" when trying to run a Python script on Linux? for a common problem encountered while trying to set this up on Linux/Mac, or 'From/import' is not recognized as an internal or external command, operable program or batch file for the equivalent problem on Windows.


Solution

    1. Add a shebang line to the top of the script:

      #!/usr/bin/env python

    2. Mark the script as executable:

      chmod +x myscript.py

    3. Add the dir containing it to your PATH variable. (If you want it to stick, you'll have to do this in .bashrc or .bash_profile in your home dir.)

      export PATH=/path/to/script:$PATH