【问题标题】:How do you import files into the Python shell?如何将文件导入 Python shell?
【发布时间】:2014-12-16 08:08:01
【问题描述】:

我制作了一个示例文件,它使用了一个名为Names 的类。它有它的初始化函数和一些方法。当我创建类的实例时,它会检索实例的名字和姓氏。其他方法问候实例并说出离开消息。我的问题是:如何在不运行模块本身的情况下将此文件导入 Python shell?

我的文件名是classNames.py,位置是C:\Users\Darian\Desktop\Python_Programs\Experimenting

我的代码如下所示:

 class Names(object):
     #first function called when creating an instance of the class
     def __init__(self, first_name, last_name):
         self.first_name = first_name
         self.last_name = last_name

      #class method that greets the instance of the class.
      def intro(self):
          print "Hello {} {}!".format(self.first_name, self.last_name)

      def departure(self):
          print "Goodbye {} {}!".format(self.first_name, self.last_name)

但我得到了错误:

Traceback (most recent call last): 
  File "<pyshell#0>", line 1, in <module> 
    import classNames.py 
ImportError: No module named classNames.py

【问题讨论】:

  • 正在导入(第一次)正在运行。
  • 你的意思是什么我如何将这个文件导入python shell而不需要运行模块本身
  • “导入而不运行模块”是什么意思?
  • 例如,当我运行 shell 时,我可以导入数学库,而无需打开代码并运行它。有没有办法用我的文件做到这一点?我之前在同一个目录中创建了一个新文件并在同一个文件夹中导入了不同的文件时已经这样做了,但那是在 Python IDLE 中。 @BrenBarn
  • 编辑问题以包含(代码格式的)错误消息。简短的回答是 Python 不知道在哪里寻找你的文件。参见例如docs.python.org/2/tutorial/modules.html#the-module-search-pathstackoverflow.com/q/12257747/3001761

标签: python class python-2.7


【解决方案1】:

我不清楚您期望什么以及您看到什么,但是您的模块的处理方式与math 和任何其他模块完全一样:

您只需导入它们。如果这是第一次发生,则获取并执行该文件。运行它后留在其命名空间中的所有内容都可供您从外部使用。

如果您的代码仅包含 defclass 语句和赋值,您将不会注意到任何事情发生,因为此时没有“真正”发生。但是您有可用的类、函数和其他名称。

但是,如果您在顶层有 print 语句,您会看到它确实被执行了。

如果你在 Python 路径中的任何地方都有这个文件(无论是明确的还是因为它在当前工作目录中),你可以像这样使用它

import classNames

并使用其内容如

n = classNames.Names("John", "Doe")

或者你做

from classNames import Names
n = Names("John", "Doe")

不要这样做import classNames.py,因为这会尝试从包classNames/ 导入模块py.py

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    相关资源
    最近更新 更多