在python解释器中执行多行时出错
我正在试验python和一个良好的编码环境。作为一种解释性语言,我希望逐行执行代码,并在编写脚本之前了解发生了什么。我试着在python解释器中运行这个简单的代码。(我在ubuntu上使用python 2.7) 它作为脚本执行得非常好。但当我在解释器上尝试时:在python解释器中执行多行时出错,python,ubuntu,compiler-errors,Python,Ubuntu,Compiler Errors,我正在试验python和一个良好的编码环境。作为一种解释性语言,我希望逐行执行代码,并在编写脚本之前了解发生了什么。我试着在python解释器中运行这个简单的代码。(我在ubuntu上使用python 2.7) 它作为脚本执行得非常好。但当我在解释器上尝试时: >>> from time import localtime\ ... print ('time is', localtime()) 我得到以下错误: File "<stdin>", line 2
>>> from time import localtime\
... print ('time is', localtime())
我得到以下错误:
File "<stdin>", line 2
print(localtime())
^
SyntaxError: invalid syntax
我得到:
('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
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
名称错误:未定义名称“\uuuuu文件\uuuuu”
追加此行时会出现此错误
python交互式shell中的os.path.join(os.path.dirname(文件)
pythonshell在文件中未检测到当前文件路径,并且
与添加此行的文件路径相关
因此,您应该编写以下行os.path.join(os.path.dirname(文件)
在file.py中。然后运行python file.py,因为它需要
您的文件路径。
这就是第二个问题的答案
第一个问题很简单,您忘记了打印括号(localtime())
为什么在第一行末尾加反斜杠?我用它来执行多行。这不是必需的吗?比如我可以执行import语句,然后执行print语句吗?你会得到同样的错误吗?我也尝试了另一段代码。请检查编辑您不需要反斜杠来执行多个语句。反斜杠用于将一条语句拆分为多行。每条语句都应该在自己的行上,换行时不能使用反斜杠。
>>>import os
>>>print os.path.dirname(__file__)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
>>> 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)
>>>