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

2024-05-16 14:28:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

-我的目录/数据.py地址:

Parameter=10

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

我的目录/主.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非常陌生,很难跟随其他类似的帖子。有人能回答这个问题吗?你知道吗


Tags: andtheto数据py目录脚本data
2条回答

从另一个文件读取参数

你可以用

import Data

或者

from Data import *

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

或者,如果您只想为一个示例“参数”导入一个变量或函数,那么可以这样使用

from Data import Parameter

要在导入后使用变量,只需使用如下所示的变量名。你知道吗

print Data.Parameter

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

为此,只需在main函数中使用一个变量来存储它。要修改函数中的变量,请使用“全局”变量指定引用的是全局变量,它将作为局部变量。你知道吗

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

加载数据.py通过exec

你知道吗主.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))

相关问题 更多 >