简体   繁体   中英

How to make Python script portable to machines with interpreters in different locations?

I'm sure this is well documented somewhere, but I can't find it! I want to make my scripts portable to machines that may not have their Python interpreters in the same location. For that reason, I thought that I could just code the first line as #!python3 rather than with the absolute path to the interpreter, like #!/usr/local/bin/python3 .

No doubt most of you understand why this doesn't work, but I have no idea. Although my lab mates aren't complaining about having to recode my scripts to reflect the absolute path to the interpreter on their own machines, this seems like it shouldn't be necessary. I'd be perfectly happy with a response providing a link to the appropriate documentation. Thanks in advance.

The path given after #! in the shebang line is an absolute path, so simply python3 does not work. You should use

#!/usr/bin/env python3

to look up python3 in the PATH on a POSIX machine. Of course this will only find the Python interpreter if it is in some directory given in the PATH environment variable.

env is a program that handles these sort of things. You should pretty much always use something like #! /usr/bin/env python3 #! /usr/bin/env python3 as your shebang line rather than specifying an absolute path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM