多次在另一个脚本中运行python脚本

时间:2016-07-17 04:48:35

标签: python multifile

我有一个包含一些数据的python脚本:

-My_Directory / Data.py:

Parameter=10

我还有一个Main.py脚本,应该多次调用Data.py

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

我应该如何编写Main.py脚本来完成任务?

我是python的新手,我很难跟随其他类似的帖子。有人请回答这个问题吗?

2 个答案:

答案 0 :(得分:1)

通过 exec

将Data.py内容加载到命名空间

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

答案 1 :(得分:0)

从另一个文件中读取参数

你可以使用

import Data

from Data import *

显式导入Data.py的所有变量和函数。 (如果导入文件在同一个目录中)

或者如果你只想为一个例子导入一个变量或函数"参数",那么就像这样使用

from Data import Parameter

在导入后使用变量只需使用变量名称如bellow。

print Data.Parameter

我假设您不打算将变量存储回Data.py文件中。如果您没有将可变数据存储回物理文件,我建议使用全局变量来存储来自引用文件的数据,并在Main.py中引用它。

这样做只需使用main函数中的变量来存储它。修改函数中的变量使用" global"变量用于指定您引用的是全局变量,它将作为局部变量。

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