1

My script has this at the first line:

#!/usr/bin/python3.6

But in different system python3.6 is installed at different locations, such as:

/user/bin/python3.6 /tools/bin/python3.6 /user/local/bin/python3.6 

How can I make my script good at the these 3 systems?

6
  • Why is this tagged "bash"? Bash isn't involved in parsing the shebang -- that's done by your OS kernel. (Strictly, some shells will try to do it themselves as a fallback if the OS reports a failure in the execve() syscall or its local equivalent, but it's the operating system kernel's job; the shell implementations, when/where they exist, are just as a fallback/workaround for OS bugs). Commented Sep 10, 2021 at 18:10
  • Shebangs are not meant to provide portability. They are instructions to the local kernel as to where the interpreter is located. It can and should be set as appropriate at installation time, rather than given a one-size-fits-all value when the script is written. Commented Sep 10, 2021 at 18:12
  • @CharlesDuffy You’re correct but I’ve re-tagged this as shell nonetheless, since the shebang line is conceptually linked to the shell. The fact that the shell forwards this to the OS (IIRC via execve?) is something few people realise, and also doesn’t affect this question. Commented Sep 10, 2021 at 18:12
  • @KonradRudolph Maybe we should then emphasize that it's not something the shell uses itself. Commented Sep 10, 2021 at 18:13
  • 2
    The shell doesn't forward anything; the OS itself looks at the first few bytes of an executable to see what its format is. The bytes #! are interpreted as introducing a path to use as an interpreter. The shell's only involvement is when the OS decides it can't execute the file, at which point the shell may try something else. (bash, for example, forks itself to execute the file as a bash script; othershells assume the default system shell should be used.) Commented Sep 10, 2021 at 18:15

1 Answer 1

3

There are broadly two alternatives:

  1. Don’t hard-code the path; instead, use env to determine the path:

    #!/usr/bin/env python3 
  2. Or don’t write scripts with a shebang line at all; instead, create a proper package with a setuptools installer, and instruct setuptools to create an executable file with the proper interpreter set for the target system.

For anything that’s more than a quick & dirty script, or a script purely intended for local consumption, the second choice is more maintainable, and constitutes the “proper” way of doing this.

Sign up to request clarification or add additional context in comments.

1 Comment

#2 is definitely preferable; the version of Python your script expects may not be the primary version of Python specified by the user's environment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.