10

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?

shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
Laurenz ebs
  • 191
  • 1
  • 9
  • Shebangs are literal. You need to know the Python version you have and want to use beforehand. – heemayl Feb 14 '18 at 11:34
  • 1
    If you are going to be packaging this, you can specify a detailed requirement in `setup.py`. I would recommend against using the shebang for this. Maybe check `sys.version_info` in your script, though that obviously requires the script to parse in the first place. – tripleee Feb 14 '18 at 11:34
  • I wouldn't call it a dupe because of the [current situation with 3.6](https://askubuntu.com/questions/946112/what-with-python-3-6), and this one is specific to the exact python version (3.6+) instead of just py3. – shad0w_wa1k3r Feb 14 '18 at 11:42
  • 2
    The accepted answer in the linked question isn't very helpful here, but [the answer by Gravity Grave](https://stackoverflow.com/a/41901923/4014959) shows how to access `sys.version_info`, which _is_ relevant, IMHO, and it has the benefit that it works on all platforms, not just *nix. – PM 2Ring Feb 14 '18 at 11:49
  • 3
    SyntaxError occur at compile time before the module is "executed". So you can't check the exact Python version from a shebang. – glenfant Feb 14 '18 at 11:52
  • 1
    Very good point @glenfant. And therefore you can't use `sys.version_info` either, so I re-opened the question. – PM 2Ring Feb 14 '18 at 12:00

1 Answers1

9

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}\"")
shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
glenfant
  • 1,298
  • 8
  • 9
  • 1
    Nice work. I'd probably change the OP's f-string to avoid escaping the double-quotes: `f'The variable contains "{testvar}"'` – PM 2Ring Feb 14 '18 at 12:42