python - 在python解释器中执行多行时出错

标签 python ubuntu compiler-errors

我正在尝试使用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/

相关文章:

linux - 加载共享库 : libevent-1. 4.so.2 时出错:无法打开共享对象文件:

c - GCC 编译器拒绝查看 Main 方法(C 编程)

python - 安装 Tensorflow 警告 : Value for scheme. 脚本不匹配

python - 以内存有效的方式迭代添加 pandas 数据帧

python - 如何用 SHAP 值来解释我的部分预测? (并不是每一个预测)

c - 使用 TCP/IP 协议(protocol)的 c 中的服务器客户端应用程序

python - Matplotlib 绘图速度过慢

linux - 为什么 Ubuntu 默认启动分区这么小?我怎样才能增加它?

ubuntu - SSH 网络错误 : Connection refused

java - 当我使用 IntelliJ 构建代码时出现错误