How to write shebang when using features of minor versions

Laurenz ebs Source

For example:

testvar = "test"
print(f"The variable contains \"{testvar}\"")

Formatted string literals were introduced in python3.6

if i use #!/usr/bin/env python3, it will throw a syntax error if there is an older version of python installed.
If i use #!/usr/bin/env python3.6, it won't work if python3.6 isn't installed, but a newer version is.

How do i make sure my program runs on a certain version and up? I can't check the version if using python3, since it won't even start on lower versions.

Edit:

I don't mean how to run it, of course you could just explicitly say "run this with python3.6 and up", but what is the correct way to make sure the program is only ran with a certain version or newer when using ./scriptname.py?

pythonpython-3.xposixshebang

Answers

answered 6 months ago glenfant #1

You need to split your script in 2 modules to avoid the SyntaxError: The first one is the entry point that checks Python version and imports the app module if the python version does not the job.

# main.py: entry point
import sys

if sys.version_info > (3, 6):
    import app
    app.do_the_job()
else:
    print("You need Python 3.6 or newer. Sorry")
    sys.exit(1)

And the other:

# app.py
...
def do_the_job():
    ...
    testvar = "test"
    ...
    print(f"The variable contains \"{testvar}\"")

comments powered by Disqus