简体   繁体   English

在多个文件中使用导入的模块

[英]Using imported modules in more than one file

This question is a bit dumb but I have to know it. 这个问题有点愚蠢,但我必须知道。 Is there any way to use imported modules inside other imported modules? 有什么办法可以在其他导入的模块中使用导入的模块吗?

I mean, if I do this: 我的意思是,如果我这样做:

-main file- -主文件-

import os  
import othermodule  

othermodule.a()

-othermodule- -其他模块-

def a():
  return os.path.join('/', 'example') # Without reimporting the os module

The os module is not recognized by the file. 该文件无法识别os模块。 Is there any way to "reuse" the os module? 有什么办法可以“重用” os模块吗?

There's no need to do that, Python only loads modules once (unless you unload them). 无需这样做,Python仅加载一次模块(除非您卸载它们)。

But if you really have a situation in which a module can't access the standard library (care to explain???), you can simply access the os module within the main module (eg mainfile.os , modules are just variables when imported into a module namespace). 但是,如果您确实遇到模块无法访问标准库的情况(需要解释一下???),则可以简单地访问主模块中的os模块(例如mainfile.os ,模块在导入时只是变量)进入模块名称空间)。

If the os module is already loaded, you can also access it with sys.modules["os"] . 如果os模块已经加载,则也可以使用sys.modules["os"]

You have to put import os in othermodule.py as well (or instead, if "main file" doesn't need os itself). 您还必须将import os放在othermodule.py中(或者,如果“ main file”不需要os本身)。 This is a feature; 这是一个功能; it means othermodule doesn't have to care what junk is in "main file". 这意味着othermodule不必关心“主文件”中的垃圾内容。 Python will not read the files for os twice, so don't worry about that. Python不会两次为os读取文件,因此不必担心。

If you need to get at the variables in the main file for some reason, you can do that with import __main__ , but it's considered a thing to be avoided. 如果出于某种原因需要获取主文件中的变量,则可以使用import __main__做到这一点,但这被认为是可以避免的事情。

If you need a module to be reread after it's already been imported, you probably should be using execfile rather than import . 如果需要在导入模块后重新读取模块,则可能应该使用execfile而不是import

Python only imports a module once. Python仅一次导入一个模块。 Any subsequent import calls, just access the existing module object. 任何后续的导入调用,只需访问现有的模块对象即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM