Admia
Admia

Reputation: 1144

Runnuing a python script within another script many times

I have a python script that includes some data:

-My_Directory/Data.py:

Parameter=10

I also have a Main.py script, in which the Data.py should be called many times:

My_Directory/Main.py

call the Data.py to access parameter 
Manipulating and changing  parameter
          Some Code Here
call the Data.py to access parameter 
Manipulating and changing  parameter

How should I write the Main.py script to do the task?

I am very new to python and it is hard for me to follow the other similar posts. Would someone please answer this question?

Upvotes: 0

Views: 61

Answers (2)

cwahls
cwahls

Reputation: 753

Load Data.py contents in to the namespace by exec

Main.py

while True:
    exec(open('Data.py').read())
    if Parameter > some_number: # depends on your needs
        Parameter -= 1 # depends on your needs
    with open('Data.py','w') as f: # write back to file
        f.write('Parameter = {}'.format(Parameter))

Upvotes: 0

Janaka Poddalgoda
Janaka Poddalgoda

Reputation: 21

reading parameters from another file

you can use

import Data

or

from Data import *

to explicitly import all the variables and functions of the Data.py. (if the importing file is in the same dir)

or if you want to import only one varible or function for an example "Parameter", then use like this

from Data import Parameter

to use the variable after importing just use the variable name like bellow.

print Data.Parameter

I am assuming you are not going to store the variable back in the Data.py file. If you are not storing the variable data back to physical file, i would recommend using a global variable to store data from the referencing file and refer it within the Main.py.

to do that just use a variable within the main function to store it. to modify the variable within functions use "global" variable to specify that you are referring a global variable, it will take as a local variable.

global testVar=20
testVar=20
def abc():
    global testVar
    print testVar

Upvotes: 1

Related Questions