How do you specify the shebang line of a command s

2019-05-08 05:27发布

I have created a package that I will be distributing throughout the company that replaces a legacy bash script with the same name. It is referenced many places so it needs to execute like the current script does. This has worked fine until I encountered some servers that do not have a current version of Python as the default Python (aka CentOS).

Is there a way to specify in the setup.py what shebang line is created at the top of the script file? i.e. I need #!/opt/bin/python rather than #!/usr/bin/env python.

3条回答
迷人小祖宗
2楼-- · 2019-05-08 05:56

First understand why shebang is needed -
Using a shebang lets the system know which command to use to run the script.

What does that mean?
It means when you simply execute your script like this in the terminal -

$ ./script.py

"script.py" is given as an argument to the command you have mentioned in the commandline.

So, if the shebang points to the python interpreter, the above command would be equivalent to this -

$ python script.py

So now you can understand the purpose of shebang - It just gives the path of the script interpreter. (in your case, the python interpreter).

Note, that shebang is meaningless if you execute your script like this -

$ python script.py

(This is because you are calling the python executable and passing script.py as the first argument and it simply ignores the first line as it is a comment for it.)

So, coming to your problem now - If you have two python installations and you want to execute your script using the non default python installation, what you do is either -
1. simply execute as $ /opt/bin/python script.py and ignore the shebang.
OR
2. Change script.py's shebang you can and then you can execute as ./script.py

I would choose the 1st option if I had to run script.py just once, and the 2nd one if I had to execute it many times (so I don't waste time writing /opt/bin/python every time)

查看更多
神经病院院长
3楼-- · 2019-05-08 06:00
  • Run the script with /opt/bin/python script.py, or
  • edit the first line to read #!/opt/bin/python, or
  • put /opt/bin in your path before /usr/bin.
查看更多
我只想做你的唯一
4楼-- · 2019-05-08 06:02

The answer to my question was answered by Keith. Running the setup.py as /opt/bin/python setup.py install produces the results I need without any user intervention.

查看更多
登录 后发表回答