我正在尝试使用python和良好的编码环境。作为一种解释型语言,我想逐行执行代码并了解在编写脚本之前会发生什么。我尝试在python解释器中运行此简单代码。 (我在使用python 2.7的ubuntu上)
from time import localtime
print ('time is', localtime())
这可以很好地作为脚本执行。但是当我在解释器上尝试时:
>>> from time import localtime\
... print ('time is', localtime())
我收到以下错误:
File "<stdin>", line 2
print(localtime())
^
SyntaxError: invalid syntax
当我从终端运行它时:
$ python test.py
我得到:
('time is', time.struct_time(tm_year=2017, tm_mon=3, tm_mday=19, tm_hour=20, tm_min=53, tm_sec=11, tm_wday=6, tm_yday=78, tm_isdst=1))
编辑:
第二个代码:
>>>import os
>>>print os.path.dirname(__file__)
返回:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
最佳答案
This error comes when you append this line os.path.join(os.path.dirname(file)) in python interactive shell.
Python Shell doesn't detect current file path in file and it's related to your filepath in which you added this line
So you should write this line os.path.join(os.path.dirname(file)) in file.py. and then run python file.py, It works because it takes your filepath. That's the answer to the second question.
第一个问题很简单,您忘记了括号print(localtime())
>>> from time import localtime
>>> print ('time is ',localtime())
time is time.struct_time(tm_year=2017, tm_mon=3, tm_mday=20, tm_hour=4, tm_min=32, tm_sec=55, tm_wday=0, tm_yday=79, tm_isdst=0)
>>>
关于python - 在python解释器中执行多行时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42895105/