如何解决导入和重新加载问题

2024-10-02 22:33:10 发布

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

我有一个带有tkintergui的基本工具,它通过一个行测试进行循环,然后允许通过一个单独的测试模块对一个新服务进行测试。我有一个问题,重新测试只是给出了相同的数据,作为前所以补充导入库重新加载(test)解决了这个问题,但是现在代码运行了两次。你知道吗

我试过加一个这样的柜台

if n = 0:
   import(test)
   n=n+1
else: 
    reload(test)

但是在第二个循环中我得到了错误

UnboundLocalError: local variable 'test' referenced before assignment

以及

n = 1
import test as n
n=n+1

但是n不再是一个变量。你知道吗

我需要测试运行一次,然后用新数据重新加载第二个测试


Tags: 模块工具数据testimportiflocal错误
1条回答
网友
1楼 · 发布于 2024-10-02 22:33:10

第一个文件是mytestmain.py文件。它在一个单独的模块中调用一个测试函数我的测试.py。你知道吗

# Load file mytest.py from the working directory.
# The calling file is "mytestmain.py", also in the working directory.

import mytest
print(mytest)
# output example: <module 'mytest' from 'c:\\python\\so\\mytest.py'>

data1 = 2
answer1 = 4 

data2 = 3
answer2 = 10 

# Call function "test" inside "mytest.py" module.
# Function "test" calculates a square of a number.

# Test1 with data1=2. Test answer1 is 4.
# This is the correct answer, test should pass.
result = mytest.test(data1, answer1)
print("Result1: ", result)

# Test2 with data2=3.  Test answer2 is 10.
# This is the wrong answer, test should fail.
result = mytest.test(data2, answer2)
print("Result2: ", result)

第二个文件是我的测试.py,具有测试功能。此文件只加载一次。你知道吗

# testing module, named mytest.py

def test(data, answer):
    if data:
        # If data exists, compare with answer.
        if answer == data * data:
            return "Pass"
        else:
            return "Fail"  

# Call test function.
# result = test(2, 4)
# print(result)            

# result = test(3, 10)
# print(result)  

只有在中更改参数时才需要重新加载我的测试.py文件。对于测试,通常的工作流程是将新参数传递到测试文件中,而不是尝试从测试文件内部更改这些参数。我看到在Jupyter笔记本中经常使用reload,人们在一个大型项目中尝试各种参数,这些项目被拆分成多个笔记本。单独的笔记本没有提供不同的功能。它们被分开以使每个文件更短,但所有文件都是一个单元。你知道吗

相关问题 更多 >