How to write shebang when using minor functions

For instance:

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 generate a syntax error if an older version of python is installed.

If I use #!/usr/bin/env python3.6, it will not work if python3.6 is not installed, but a newer version.

How can I make sure that my program runs on a specific version and higher? I can’t check the version if I use it python3, since it doesn’t even start in lower versions.

Edit:

I don’t mean how to run it, of course, you can just say “run it with python3.6 and higher”, but what is the right way to make sure that the program only works with a certain version or newer when used ./scriptname.py?

+4
source share
1 answer

You need to split your script into 2 modules in order to avoid SyntaxError: the first is an entry point that checks the Python version and imports the application module if the python version does not do 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 other:

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

Source: https://habr.com/ru/post/1693629/


All Articles