简体   繁体   English

从文件导入python模块

[英]Import python modules from files

How do I import modules from *py file? 如何从* py文件导入模块? I have file pythonScript.py with lines: import os, sys. 我有以下行的文件pythonScript.py:import os,sys。 If I import the file pythonScript these lines does not execute. 如果我导入文件pythonScript,这些行将不会执行。 Usung one on these modules I'm getting name error. 在这些模块上使用Usung我遇到名称错误。

It sounds like you haven't fully understood the way imports work. 听起来您还没有完全了解导入的工作方式。

If you run: 如果您运行:

import my_module

then anything contained in the my_module.py module is namespaced to my_module . 然后, my_module.py模块中包含的所有内容都将命名为my_module So to use this module, you would have to type: 因此,要使用此模块,您必须输入:

result = my_module.some_function(1,2,3,4)
object1 = my_module.SomeClass()

Similarly, if you really want to use the os import from my_module , you have to access it by: 同样,如果您确实要使用my_moduleos导入,则必须通过以下方式访问它:

my_module.os

If you import using: 如果您使用以下方式导入:

from my_module import *

then you can access os directly, but it is worth noting that wildcard (*) imports are not recommended. 那么您可以直接访问os ,但是值得注意的是,不建议使用通配符(*)导入。

Just import os again in your python terminal. 只需在python终端中再次import os

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

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