[英]How can I always pass the current variable value into a python function?
I have a project where I want the user to specify input parameters in an excel sheet that is then read into multiple functions within a class with openpyxl. 我有一个项目,我希望用户在excel表中指定输入参数,然后使用openpyxl将其读入类中的多个函数。 My problem is that, whenever I change a value in the sheet I have to run the script again to make the changes effective. 我的问题是,每当我更改工作表中的值时,我必须再次运行脚本以使更改生效。 As I want to use the script interactively and quickly show different values, this takes to much time. 由于我想以交互方式使用脚本并快速显示不同的值,因此需要花费很多时间。
Is there another way to always pass the changed variable from the sheet into the functions? 还有另一种方法可以将已更改的变量从工作表传递到函数中吗?
Here is my code: 这是我的代码:
class input:
def __init__(self, vals=None):
self.vals = vals
self.wb = load_workbook("input.xlsx", data_only = True)
self.ws = self.wb.get_active_sheet()
def get_var(self):
self.var = self.ws["B3"].value
return self.var
wb.save()
input.input()
Before getting values from an excel sheet, I had the parameters in another module which was imported into the main module. 在从Excel工作表中获取值之前,我将另一个模块中的参数导入到主模块中。 I had the same problem there but figured that was caused by the import command. 我在那里遇到了同样的问题但是认为这是由import命令引起的。 I the looked into reloading module but does not seem to solve the problem. 我看了重装模块,但似乎没有解决问题。 Then I introduced the functions which I thought would do it but no success. 然后我介绍了我认为会做的功能,但没有成功。
Any help on this would be appreciated, thanks! 任何有关这方面的帮助将不胜感激,谢谢!
The problem with your code is that you return before you save anything and you aren't using the save command correctly. 代码的问题在于,在保存任何内容之前返回并且未正确使用save命令。 Below I provided some sample code that will accept an input, modify a specific cell, and then save the file. 下面我提供了一些示例代码,它将接受输入,修改特定单元格,然后保存文件。 There is no need for a reload. 无需重新加载。 I also modified some of the variable/function names as input
is a built-in function and shouldn't be used for class names. 我还修改了一些变量/函数名称,因为input
是内置函数,不应该用于类名。 This is just to show you how to get the save working properly as I don't know what you actually want the code to do. 这只是为了向您展示如何使保存正常工作,因为我不知道您实际想要代码执行什么。
import openpyxl as op
class excel:
def __init__(self, vals=None):
self.vals = vals
self.wb = op.load_workbook("sample.xlsx", data_only=True)
self.ws = self.wb.active
def set_var(self, num):
self.ws["A1"].value = num
self.wb.save('sample.xlsx')
print(self.ws["A1"].value)
excel_file = excel()
while True:
a = input()
excel_file.set_var(a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.