Reputation: 2711
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.
Upvotes: 3
Views: 915
Reputation: 7834
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 *
Upvotes: 2
Reputation: 107152
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()
Upvotes: 3
Reputation: 2071
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 *
Upvotes: 0
Reputation: 54262
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()
Upvotes: 0