[英]How do I import other scripts?
OK, I tried looking up the question but I'm getting a lot of answers that confuse me(sorry for my ignorance). 好吧,我试着查看问题,但是我得到了许多令我困惑的答案(对不起我的无知)。 I wrote a script, and I want to import another script so that when i run it in the terminal it will be as if the second script is part of the first.
我写了一个脚本,我想导入另一个脚本,这样当我在终端中运行它时,就好像第二个脚本是第一个脚本的一部分。 How do I do this?
我该怎么做呢? I appreciate any help.
我感谢任何帮助。
Lets say you want a.py
to use b.py
. 假设你想让
a.py
使用b.py
If the code in b.py
is written outside of any function or class, all you need to do to run it is simply: 如果
b.py
的代码是在任何函数或类之外编写的,那么运行它所需的只需:
import b
If however the code is in some function, for example: 但是,如果代码在某些功能中,例如:
# Code in b.py
def some_func():
# Implementation
Then you'll need to either: 然后你需要:
import b
b.some_func()
or: 要么:
from b import some_func
some_func()
Finally, if you're code is in a function in a class, for example: 最后,如果您的代码是在类中的函数中,例如:
# Code in b.py
class ClassB():
def some_func(self):
# Implementation
you can: 您可以:
from b import ClassB
obj_b = ClassB()
obj_b.some_func()
If you want the script to just be inserted inline (like a #include), then you're Doing It Wrong. 如果你想让脚本直接插入(比如#include),那么你就是在做错了。
This will import all of the symbols from your other script as if they were defined locally (with the exception that global variable access in the imported code will be scoped to the imported module, not the local module). 这将导入其他脚本中的所有符号,就好像它们是在本地定义的一样(除了导入代码中的全局变量访问将限定为导入的模块,而不是本地模块)。
from OtherScript import *
If you have a script named first.py
: 如果你有一个名为
first.py
的脚本:
def print_something():
print("something")
You can then import
that from another script (in the same directory): 然后,您可以从另一个脚本(在同一目录中)
import
该脚本:
import first
first.print_something()
Import, so if the other script is named FirstScrity.py 导入,因此如果其他脚本名为FirstScrity.py
import FirstScript
To use something from that script you have to do FirstScript."NAME OF THING TO USE" 要使用该脚本中的某些内容,您必须执行FirstScript。“要使用的名称”
If your dont wanna do that you can do 如果你不想这样做,你可以做到
from FirstScript import "NAME OF THING TO USE"
or 要么
from FirstScript import *
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.