VSCode终端正常运行的Python程序在Mac终端报错求解决方案
问题分析与解决方法
问题根源
这是Python版本差异导致的小问题:VSCode终端默认使用Python3,而Mac系统终端大概率默认调用Python2。Python2的input()函数会把用户输入的内容当作Python代码执行,输入7:30时,它会将其识别为语法错误的代码;而Python3的input()是直接获取字符串输入,所以在VSCode中运行正常。
解决方法
方法一:指定Python3运行脚本
在Mac终端执行脚本时,不要用python mealtime.py,改用:
python3 mealtime.py
这样就会调用Python3解释器,和VSCode的运行环境一致,问题直接解决。
方法二:兼容Python2(可选)
如果需要脚本同时支持Python2和Python3,把代码里的input()替换为raw_input()——Python2的raw_input()和Python3的input()功能一致,都是直接获取用户输入的字符串。修改后的代码如下:
def main(): user_time = str(raw_input("What time is it? ")) converted = convert(user_time) if converted <= 8 and converted >= 7: print("Breakfast time!") elif converted <= 13 and converted >= 12: print("Lunch time!") elif converted <= 19 and converted >= 18: print("Dinner time!") else: print("Bed time..") def convert(time): splitted = time.split(":") converted = int(splitted[0]) + (int(splitted[1])/60) return converted if __name__ == "__main__": main()
注:更推荐方法一,因为Python2已停止官方维护,优先使用Python3环境。
内容的提问来源于stack exchange,提问作者Myat Kaung Htet
相关产品推荐
相关产品推荐

