Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to link multiple scripts?

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?

like image 352
drjrm3 Avatar asked Jan 27 '12 01:01

drjrm3


People also ask

Can I have 2 scripts in HTML?

An HTML page can contain multiple <script> tags in the <head> or <body> tag. The browser executes all the script tags, starting from the first script tag from the beginning.

How do I add multiple script tags in HTML?

Multiple <SCRIPT> Tags Up to this point all of the JavaScript Code was in one <SCRIPT> tag, this does not need to be the case. You can have as many <SCRIPT></SCRIPT> tags as you would like in a document.


3 Answers

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.

like image 191
mitch Avatar answered Nov 15 '22 08:11

mitch


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().

like image 23
Islam MT Avatar answered Nov 15 '22 09:11

Islam MT


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)
...
like image 33
Dustin Rohde Avatar answered Nov 15 '22 10:11

Dustin Rohde