无法在脚本中导入导入日期时间

无法在脚本中导入导入日期时间

本文介绍了无法在脚本中导入导入日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从python脚本导入日期时间,但可以从终端命令行导入。

I cannot import datetime from a python script, but I can from the terminal command line.

1)import datetime
2)From datetime import datetime

month = datetime.datetime.now().strftime("%B")
print month

这些代码行在命令行
中一一输入时起作用。

These lines of code work when entered one by one into the command lineAny ideas?

我在Mac上运行2.7

I'm running 2.7 on mac

推荐答案

这是怎么回事:


  1. 您将文件命名为 datetime.py 进行测试

  2. 然后您在其中写入了 import datetime ,因为这是您要试用的模块

  1. you named your file datetime.py for testing
  2. then you wrote import datetime inside it, because that's the module you want to try out

运行文件时会发生以下情况:

What happens when you run the file, is that:


  1. Python首先在本地目录中查找名为的模块 datetime

  2. 由于Python仅找到您的原始文件,因此它会生成一个名为 datetime.pyc ,因为它希望您以此为基础

幸运的是,StackOverflow的好人使您意识到了这种命名方式错误,并且您将 datetime.py 文件重命名为其他名称。但是令人困惑的是,您仍然仍然遇到错误,并且挫败感逐渐增强...

Luckily, the nice people at StackOverflow made you aware of this naming error, and you renamed your datetime.py file to something else. But confusingly you still get errors and the frustration slowly builds...


  1. 始终确保文件名不等于要导入的任何Python模块

  2. 如果您仍然忘记了,请确保删除或将重命名为本地 .py 脚本本地 .pyc 文件。这应该可以解决您的问题。 :)

  1. Always make sure that your filenames aren't equal to any Python module you want to import
  2. If you still forget, then make sure to delete or rename both the local .py script and the local .pyc file. This should fix your problem. :)

之所以如此普遍,是因为人们喜欢在编程时测试东西。而且,当他们这样做时,大多数人的自然倾向是使脚本的名称与他们要测试的名称相同。但这是大多数Python开发人员最早遇到的陷阱之一。如果设计Python的很酷的人在制作系统之前就读过Donald Norman,那将永远不是问题。但实际上,在命名文件之前,我们只需要调整Python模块系统的工作方式即可。注意:Python模块系统仍以这种方式工作仍然有其原因,但这并不妨碍它对初学者感到困惑。

The reason this is such a common error, is that people like testing stuff when programming. And when they do, the natural inclination of most people is to make a script with the same name as the thing they want to test. However that's one of the first gotchas most Python developers run into. If the cool people that designed Python read Donald Norman before making their system, this would never be a problem. But as it is, we just have to adjust to how the Python module system works before naming our files. Note: There are still reasons for the Python module system working this way, however that doesn't preclude it from being confusing to beginners.

这篇关于无法在脚本中导入导入日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 23:43