4 ms·
You couldn't be more mistaken, most libraries supported both python 2 and 3 for years. Doing what you describe is extremely trivial. If you thought it was a g
by ltbarcly3 5y ago
You couldn't be more mistaken, most libraries supported both python 2 and 3 for years. Doing what you describe is extremely trivial. If you thought it was a good idea you could write a script that would exec trampoline itself into a different interpreter version entirely.
You can also catch a SyntaxError like any other exception.
- tyingq 5y agoPut an f-string into a script and get python2 not to choke on it, or try catching that SyntaxError as you describe...without using eval, futures, or similar. You can't catch something that already happened. Yes, people are able to write backwards compatible scripts... by avoiding some features, or by using more than a single file. What I'm describing was just a desire for a very simple "this script requires python version >= X" error, with the ability to write unfettered python version X code below it, in a single file script.
- dec0dedab0de 5y agoWhat I'm describing was just a desire for a very simple "this script requires python version >= X" error, with the ability to write unfettered python version X code below it, in a single file script. import sys if sys.version_info.major < 3: raise Exception("this script requires python version >= 3") plus an extra line or two if you're worried about minor versions.
- tyingq 5y agoNow put an f-string (or other new feature that pops a syntax error) below that: print(f"whee") And run it with python2, or a python3 < 3.6.
- dec0dedab0de 5y agoahh, I see now. I would add an edit to my original comment, but it's too late.
- jaster 5y ago> cat test.py import sys if sys.version_info.major < 3: raise Exception("this script requires python version >= 3") print(f"test") > python2 test.py File "test.py", line 5 print(f"test") ^ SyntaxError: invalid syntax Doesn't seem that simple
- int_19h 5y agoIt needs to also do: from __future__ import absolute_import, division, print_function, unicode_literals This will give you syntax much closer to Python 3 in Python 2.7. The remaining differences can be papered over with function and class helpers. Well, except for metaclasses, but I doubt you'd have need for those in a single-file script.
- deleted 5y ago[deleted]
- emidln 5y agoThis isn't pretty, but it's possible: import sys if sys.version_info[0] < 3: print("Needs Python 3+") sys.exit(1) else: prog = r''' def help(): print("Help: ...") def do_spam(*args): print("spamming") def main(args): match args: case [subcommand, *args]: return globals()[f'do_{subcommand}'](*args) case _: return help() if __name__ == '__main__': try: status = main(sys.argv[1:]) sys.exit(int(status if status is not None else 0)) except Exception as e: import traceback traceback.print_exc(e) sys.exit(1) ''' compile(prog, '', 'exec') exec(prog)