Python主程序调用外部脚本处理数据出现循环导入/无限输入问题
问题根源
- 无限循环原因:你用
subprocess启动add.py/multiply.py时,脚本内from main import xxx会触发main.py全量执行,顶层的输入代码会再次运行,形成循环。 - 导入报错原因:
data_a是Input类的实例属性,既没有实例化,也不是main模块的顶层变量,无法直接从main模块导入。
解决方案
这里提供两种可行的改法,可根据需求选择:
方案1:保留子进程调用逻辑(适合必须独立运行外部脚本的场景)
步骤1:修改main.py
把执行逻辑放到if __name__ == "__main__"保护块中,避免导入时执行输入代码,同时通过命令行参数传递数据,读取子进程返回的结果:
import sys, os, math, statistics, re import subprocess import numpy as np import matplotlib.pyplot as plt # 仅当直接运行main.py时才执行以下代码,被导入时跳过 if __name__ == "__main__": '''---Data input block---''' print('-----Welcome to mainX-----') num1 = int(input('type number 1:')) num2 = int(input('type number 2:')) print('choose a tool between adding and multiplying') tool = input('multiply/add: ') '''---external program block---''' result = [] if tool == 'add': # 把num1作为参数传给add.py proc = subprocess.run(['python', 'add.py', str(num1)], capture_output=True, text=True) # 读取子进程输出的结果,转成列表 result = list(map(int, proc.stdout.strip().split(','))) elif tool == 'multiply': # 把num2作为参数传给multiply.py proc = subprocess.run(['python', 'multiply.py', str(num2)], capture_output=True, text=True) result = list(map(int, proc.stdout.strip().split(','))) '''---Plotting block---''' fig = plt.figure(figsize = (7,5)) ax = fig.add_subplot(111) TK = np.linspace(1, len(result)) # 长度和结果匹配 ax.plot(TK, result, label=f'This is the result of {tool}', c='g', linewidth=3) # 原代码xlim范围270-400和TK的1-10区间不匹配,会看不到图,需要可自行调整 # ax.set_xlim(270, 400) plt.legend(fontsize=14) plt.tight_layout() plt.show()
步骤2:修改add.py
不需要导入main,直接从命令行取参数计算后输出:
import sys # 取命令行传入的第一个参数 num = int(sys.argv[1]) addresult = [num +1, num +2, num +3] # 输出结果供主进程读取 print(','.join(map(str, addresult)))
步骤3:修改multiply.py
import sys num = int(sys.argv[1]) multiplyresult = [num *1, num *2, num *3] print(','.join(map(str, multiplyresult)))
方案2:改为模块导入调用(更简单高效,推荐)
不需要开子进程,直接把计算逻辑封装成函数导入调用,完全避免循环导入问题:
步骤1:修改add.py为模块
def add_calc(num): return [num +1, num +2, num +3]
步骤2:修改multiply.py为模块
def multiply_calc(num): return [num *1, num *2, num *3]
步骤3:修改main.py直接导入函数调用
import sys, os, math, statistics, re import numpy as np import matplotlib.pyplot as plt # 直接导入计算函数 from add import add_calc from multiply import multiply_calc if __name__ == "__main__": print('-----Welcome to mainX-----') num1 = int(input('type number 1:')) num2 = int(input('type number 2:')) print('choose a tool between adding and multiplying') tool = input('multiply/add: ') result = [] if tool == 'add': result = add_calc(num1) elif tool == 'multiply': result = multiply_calc(num2) # 绘图逻辑和方案1一致 fig = plt.figure(figsize = (7,5)) ax = fig.add_subplot(111) TK = np.linspace(1, len(result)) ax.plot(TK, result, label=f'This is the result of {tool}', c='g', linewidth=3) plt.legend(fontsize=14) plt.tight_layout() plt.show()
内容的提问来源于stack exchange,提问作者Edwin OA
相关产品推荐
相关产品推荐

