我想通过仅更改变量来多次 运行 python 文件

I want to run the python file multiple times by changing only the variable

在 jupyter 中,如果我导入另一个 Python 文件,则会执行整个文件。更改变量后,我想以相同的方式执行整个文件。

file1.ipynb

a = 5
b = 2
print(a+b)
def change(changeA,changeB):
    a=changeA
    b=chnageB

file2.ipynb

import file1
file1.change(5,7)
**execute file1 again***

假设您有一个文件:

a = 5
b = 2
print(a+b)

并且您想用新的变量值重新运行它。你可以使用一个函数:

file1

def do_computations(a, b):
    return a + b

file2

from file1 import do_computations

do_computations(1,1)
do_computations(1,3)

如果你真的希望变量是全局的(不推荐),你可以这样做:

file1

a = 5
b = 2


def do():
    print(a+b)

file2

import file1

file1.a = 5
file1.b = 5

file1.do()

您发布的代码在 运行 之间不起作用,当您更改变量时,它只会更改 运行 期间的值。 运行 它将再次从原始值开始。

import file1
file1.change(5,7)
**execute file1 again***

即使它有效,或者您在同一个 运行 中使用它,您也是在为您的函数声明局部变量,它们不会更改全局变量。您必须为此使用关键字 global。同样,不推荐这种方法。

def change(changeA,changeB):
    global a
    global b
    a=changeA
    b=chnageB