我在我的MacBook上尝试了一个非常简单的代码:下面是代码
def file_name(fname):
try:
fhand = open(fname)
except:
print('File cannot be opened: ', fname)
quit()
count = 0
starts_with = **input**('Entries starts with: ')
for line in fhand:
if line.startswith(starts_with):
count = count + 1
print('There were ', count, ' subject lines in', fname)
fname =输入(‘输入文件名:') file_name(fname)
为了使代码正常工作,我不得不用input()
替换raw_input()
。我已经在我的设备上安装了python3.8,但是不能用它来运行代码。起初,我认为问题在于VS代码。在转到PyCharm专业后,我仍然有同样的,确切的问题。
重命名为raw_input()
后所需的输出是:
Hou-Pengs-MBP:PY4E houpengzhu$ python File.py
Enter the file name: hw.py
Entries starts with: print
('There were ', 1, ' subject lines in', 'hw.py')
使用input()
时输出
Hou-Pengs-MBP:PY4E houpengzhu$ python File.py
Enter the file name: hw.py
Traceback (most recent call last):
File "File.py", line 15, in <module>
fname = input('Enter the file name: ')
File "<string>", line 1, in <module>
NameError: name 'hw' is not defined
我对PyCharm的配置:
用于VS代码:
我该怎么做才能得到预期的结果呢?
UPDATE:我在Ryosuke (第二个投赞成票的答案)中发现这个解决方案对我有效:现在,我的默认版本的如何更改默认python版本?已经更改为python3。在运行该代码时,您仍然需要声明您希望python3到IDE,但这样做就不再需要使用python 2中的raw_input()来运行代码了。
发布于 2020-06-20 04:57:17
IDE并不控制终端会话。python -V
将向您展示问题所在,或者更准确地说,您正在用哪个版本执行脚本
您应该尝试运行/usr/bin/python3 hw.py
,例如对于python3.7.3或使用/usr/local/bin/python3
运行3.8.3
或者你需要激活你的静脉然后你可以只使用python
发布于 2020-06-20 04:55:24
您确定在python3上运行它吗?在python 3中,如果使用raw_input()
,则不存在python3 File.py
。
https://stackoverflow.com/questions/62481674
复制相似问题