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

后端 未结 10 1115
梦谈多话
梦谈多话 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条回答
  • 2020-12-04 10:28

    Putting the script somewhere in the PATH (like /usr/local/bin) is a good solution, but this forces all the users of your system to use/see your script.

    Adding an alias in /etc/profile could be a way to do what you want allowing the users of your system to undo this using the unalias command. The line to be added would be:

    alias MyScript=/path/to/file/MyScript
    
    0 讨论(0)
  • 2020-12-04 10:30

    i find a simple alias in my ~/.bash_profile or ~/.zshrc is the easiest:

    alias myscript="python path/to/my/script.py"

    0 讨论(0)
  • 2020-12-04 10:34

    The best place to put things like this is /usr/local/bin.

    This is the normal place to put custom installed binaries, and should be early in your PATH.

    Simply copy the script there (probably using sudo), and it should work for any user.

    0 讨论(0)
  • 2020-12-04 10:34

    Type echo $PATH in a shell. Those are the directories searched when you type command, so put it in one of those.

    Edit: Apparently don't use /usr/bin, use /usr/local/bin

    0 讨论(0)
  • 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!
    
    0 讨论(0)
  • 2020-12-04 10:38

    Acording to FHS, the /usr/local/bin/ is the good place for custom scripts. I prefer to make them 755 root:root, after copying them there.

    0 讨论(0)
提交回复
热议问题