简体   繁体   中英

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 . If the code in b.py is written outside of any function or class, all you need to do to run it is simply:

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.

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 :

def print_something():
    print("something")

You can then import that from another script (in the same directory):

import first

first.print_something()

Import, so if the other script is named FirstScrity.py

import FirstScript

To use something from that script you have to do FirstScript."NAME OF THING TO USE"

If your dont wanna do that you can do

from FirstScript import "NAME OF THING TO USE"

or

from FirstScript import *

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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