How to link multiple scripts? - python

I would like to separate my functions into different files like I do with c++ (a driver file and a file for different categories of functions that I end up linking together upon compilation).
Let's suppose I want to create a simple 'driver' file which launches the main program and a 'function' file which includes simple functions which are called by the driver and other functions within the 'function' file.
How should I do this? Since python is not compiled, how do I link files together?

You can import modules. Simply create different python files and import them at the start of your script.
For example I got this function.py file :
def func(a, b):
return a+b
And this main.py file:
import function
if __name__ == "__main__":
ans = function.func(2, 3)
print(ans)
And that is it! This is the official tutorial on importing modules.

You can import any Python file simply by typing:
import filename
But in this case you have to type the file name each time you want to use it. For example, you have to use filename.foo to use the specific function foo inside that file. However, you can also do the following:
from function import *
In this case all you have to do is to directly type your commands without filename.
A clear example:
If you are working with the Python turtle by using import turtle then each time you have to type turtle.foo. For example: turtle.forward(90), turtle.left(90), turtle.up().
But if you use from turtle import * then you can do the same commands without turtle. For example: forward(90), left(90), up().

At the beginning of driver.py, write:
import functions
This gives you access to attributes defined in functions.py, referenced like so:
functions.foo
functions.bar(args)
...

Related

Importing a function from another folder

Let's say I have a structure like this:
tests----------------
___init__.py
test_functions_a
functions-----------
___init__.py
functions_a
functions_b
I want to test a function from functions_a, but inside functions_a I am importing a function from functions_b.
When I am trying:
from functions.functions_a import function_aa
I am getting an error, because inside functions_a I have a line:
from functions_b import function_bb
and not:
from functions.functions_b import function_bb
How can I solve this?
Any good practises are welcome, as I have no experience in structuring projects.
According to Google Python Style Guide, you should:
Use import statements for packages and modules only, not for
individual classes or functions. Note that there is an explicit
exemption for imports from the typing module.
You should also:
Import each module using the full pathname location of the module.
If you follow those two conventions, you will probably avoid, in the future, situations like the one you just described.
Now, here's how your code will probably look like if you follow those tips:
Module functions.functions_a:
from functions import functions_b as funcs_b
def function_aa():
print("AA")
def function_aa_bb():
function_aa()
funcs_b.function_bb()
Module functions.functions_b:
def function_bb():
print("BB")
And, finally, test_functions_a.py:
from functions import functions_a as funcs_a
if __name__ == "__main__":
funcs_a.function_aa()
funcs_a.function_aa_bb()
Output:
AA
AA
BB
You cannot directly import the function instead you could import File 1 to some other File and then call the function from that particular file you imported .

Access function in other python file within a subfolder

I am building a fairly complex python app with various scripts. I am planning on sorting these scripts into subfolders so I can then access the functions from a main file. For example having a function called main inside a file called test.py inside a subfolder called test. How would I call the function?
I have tried using
from test import main
However I get a ModuleNotFoundError error.
Thanks in advance for the help.
As mentioned here, to import files from subfolders in python, use the '.' to signify a subdirectory.
In your example, the import would be
from test.test import main
The general syntax for such an import would be the following:
from [subfolderName].[fileName] import [functionName]
To import all functions from file, the syntax would be:
import [subfolderName].[fileName]

how can I access functions from another program into my new program

I'm trying to write a program that is related to another program, so how can I access the individual functions from my previous program and work with them as required, I know you are suppose to import that program but what to do after that.
The program that I import how can I use functions from it.
It would be better if you write code.
I assume your 1st code is code1.py and you want to use fun1 from it in code2.py.
Put them in same directory . . .
Use:
import code1
code1.fun1()
Or
from code1 import *
fun1()
Note: 2nd method is not recommended.
If you want to import it from another folder you should also try to use os.chdir().
But mostly you can use either import * to import all of the functions or just import and then the functions you want to import.

Linking Python Files Assistance

I understand how to actually link python files, however, i don't understand how to get variable's from these linked files. I've tried to grab them and I keep getting NameError.
How do I go about doing this? The reason i want to link files is to simply neaten up my script and not make it 10000000000 lines long. Also, in the imported python script, do i have to import everything again? Another question, do i use the self function when using another scripts functions?
ie;
Main Script:
import sys, os
import importedpyfile
Imported Py File
import sys, os
I understand how to actually link python files, however, i don't
understand how to get variable's from these linked files. I've tried
to grab them and I keep getting NameError.
How are you doing that? Post more code. For instance, the following works:
file1.py
#!/usr/bin/env python
from file2 import file2_func, file2_variable
file2_func()
print file2_variable
file2.py:
#!/usr/bin/env python
file2_variable = "I'm a variable!"
def file2_func():
print "Hello World!"
Also, in the imported python script, do i have to import everything
again?
Nope, modules should be imported when the python interpreter reads that file.
Another question, do i use the self function when using another
scripts functions?
Nope, that's usually to access class members. See python self explained.
There is also more than one way to import files. See the other answer for some explanations.
I think what you are trying to ask is how to get access to global vars from on .py file without having to deal with namespaces.
In your main script, replace the call to import importedpyfile to say this instead
from importedpyfile import *
Ideally, you keep the code the way you have it. But instead, just reference those global vars with the importedpyfile namespace.
e.g.
import importedpyfile
importedpyfile.MyFunction() # calls "MyFunction" that is defined in importedpyfile.py
Python modules are not "linked" in the sense of C/C++ linking libraries into an executable. A Python import operation creates a name that refers to the imported module; without this name there is no (direct) way to access another module.

Python Idle and Terminal Import Differences

I just started using Python and I have a question about idle vs terminal.
In idle, I made a file called Robot.py
I have a class called Robot
class Robot(object)
def __init__(self,x,y):
#some code here etc...
def HelloWorld()
print "Hello World!"
I have another file called testrobot.py, which looks like so:
import Robot
r = Robot(1,4)
In idle, I am able to successfully create a Robot object when I run testrobot.py. However in terminal, it gives an error Message NameError: Robot is not defined
I'm not sure how to run my program in terminal.
Also:
How can I call my HelloWorld() function which is in Robots.py but not of the class Robot in an external file (such as testrobot.py)?
Thanks in advance!
When you load and run scripts in IDLE, they are automatically loaded for the interpreter. That means that as soon as you run the script in IDLE, the Python shell already has those types defined.
When you want to run it from outside of IDLE, i.e. without running the module first, you need to import your Robot from that module. To do that, you import the module, not the type:
import Robot
myRobot = Robot.Robot(...)
Or, if you want to use Robot directly, you need to use the from ... import syntax:
from Robot import Robot
myRobot = Robot(...)
Similarily, you can call your function by using Robot.HelloWorld in the first case, or directly if you add HelloWorld to the import list in the second case:
from Robot import Robot, HelloWorld
myRobot = Robot(...)
HelloWorld()
As you can see, it is generally a good idea to name your files in lower case, as those are the module names (or “namespaces” in other languages).
You are trying to create a class of an import, not the class imported.
You are trying to import a file called Robot.py with that import statement. To import your robot class you will have to type import Robot and then write Robot.Robot(1,4) to create an object of it. Alternatively you can import all references from the file: from Robot import * and then write Robot(1,4).
The reason it will work with IDLE is that it basically imports everything from the file you run, allowing you use the methods and classes in that file.

Categories