社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如果在.py文件上运行Python2由于语法错误而失败,则尝试显示自定义错误(.py文件包含f字符串)

SLater01 • 4 年前 • 819 次点击  

我尝试在文件的前几行中使用版本检查来执行此操作:

import sys
if not sys.version_info[0] == 3:
    sys.exit('You need to run this with Python 3')

# Lots of other code here....

# And then...
foo = 2
bar = 3
print(f"Some message that uses f-strings like this: variables are {foo} {bar}")

但是,当.py文件实际使用Python2运行时,它在使用f字符串的行上返回语法错误。这不太容易理解。

有没有办法可以强制程序在版本检查时失败,从而返回更有用的错误消息?

谢谢

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53682
 
819 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Martijn Pieters
Reply   •   1 楼
Martijn Pieters    4 年前

有没有办法可以强制程序在版本检查时失败,从而返回更有用的错误消息?

支持的语法 在文件中,Python 2无法解析f字符串。

您必须将项目分成多个模块,并且在 要导入的第一个模块 (比如说,最高层 __init__.py

或者 . 相反,设置 python_requires