How do I install a script to run anywhere from the command line?

后端 未结 10 1120
梦谈多话
梦谈多话 2020-12-04 10:14

If I have a basic Python script, with it\'s hashbang and what-not in place, so that from the terminal on Linux I can run

/path/to/file/MyScript [args]
         


        
10条回答
  •  -上瘾入骨i
    2020-12-04 10:35

    The quick answer is to symlink your script to any directory included in your system $PATH.

    The long answer is described below with a walk through example, (this is what I normally do):

    a) Create the script e.g. $HOME/Desktop/myscript.py:

    #!/usr/bin/python
    print("Hello Pythonista!")
    

    b) Change the permission of the script file to make it executable:

    $ chmod +x myscript.py

    c) Add a customized directory to the $PATH (see why in the notes below) to use it for the user's scripts:

    $ export PATH="$PATH:$HOME/bin"

    d) Create a symbolic link to the script as follows:

    $ ln -s $HOME/Desktop/myscript.py $HOME/bin/hello

    Notice that hello (can be anything) is the name of the command that you will use to invoke your script.

    Note:

    i) The reason to use $HOME/bin instead of the /usr/local/bin is to separate the local scripts from those of other users (if you wish to) and other installed stuff.

    ii) To create a symlink you should use the complete correct path, i.e.

    $HOME/bin GOOD ~/bin NO GOOD!

    Here is a complete example:

     $ pwd
     ~/Desktop
     $ cat > myscript.py << EOF
     > #!/usr/bin/python
     > print("Hello Pythonista!")
     > EOF
     $ export PATH="$PATH:$HOME/bin"
     $ ln -s $HOME/Desktop/myscript.py $HOME/bin/hello
     $ chmod +x myscript.py
     $ hello
    Hello Pythonista!
    

提交回复
热议问题