Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write shebang when using features of minor versions

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?

like image 708
Laurenz ebs Avatar asked Feb 14 '18 11:02

Laurenz ebs


People also ask

How do I tell a Python script to use a particular version?

As a standard, it is recommended to use the python3 command or python3. 7 to select a specific version. The py.exe launcher will automatically select the most recent version of Python you've installed. You can also use commands like py -3.7 to select a particular version, or py --list to see which versions can be used.

How do you write in shebang in Python?

#!/usr/bin/env python """ The first line in this file is the "shebang" line. When you execute a file from the shell, the shell tries to run the file using the command specified on the shebang line. The ! is called the "bang". The # is not called the "she", so sometimes the "shebang" line is also called the "hashbang".

Where should I put shebang in Python?

If you write a shebang manually then always use #!/usr/bin/env python unless you have a specific reason not to use it. This form is understood even on Windows (Python launcher). Note: installed scripts should use a specific python executable e.g., /usr/bin/python or /home/me/. virtualenvs/project/bin/python .

What is #!/ Usr bin env Python?

This is a shell convention that tells the shell which program can execute the script. #!/usr/bin/env python. resolves to a path to the Python binary.


1 Answers

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}\"")
like image 54
glenfant Avatar answered Nov 15 '22 05:11

glenfant