【发布时间】:2019-10-31 13:16:12
【问题描述】:
我遇到了一个问题,我有一个类方法,它创建一个批处理文件并将文件名存储在一个名为“文件名”的变量中。我有另一种运行批处理文件的方法,该批处理文件调用在另一种方法中创建的“文件名”。但我得到响应类对象没有属性“文件名”。如何在一个方法中创建此变量并在同一类中的另一个方法中调用它?
我试过设置 self.filename = 文件名。我尝试在类之外设置全局文件名 = None,然后在类 init 本身内设置文件名。我在下面包含了 sn-p 代码:
class SNMPPage(tk.Frame):
def __init__(self, root=None):
tk.Frame.__init__(self, root)
self.root = root
self.root.title('SNMP Get Set Test')
global filename
self.init_gui()
def create_batch(self):
i = 0
#path = os.getcwd()
global filename
#ping_set = 'ping -n 1 ' + e1.get() + ' | find "TTL=" >null\nif errorlevel 1 (\n echo host not reachable\n pause\n)\n'
snmp_get = 'snmpget' + " -Os" + " -mall " + "-c " + self.e3.get() + ' -v2c' + ' ' + self.e1.get() + ' ' + self.e2.get() + "\n"
snmp_set = 'snmpset' + " -Os" + " -mall " + "-c " + self.e3.get() + ' -v2c' + ' ' + self.e1.get() + ' ' + self.e2.get() + \
' i' + ' 1\n'
timeout = 'timeout ' + self.e4.get() + '\n'
filename = path + '\\SNMPBatchrun' + getdatetime('datetime') + ".bat"
with open(filename, 'w+') as outfile:
while i < 10:
#outfile.write(ping_set)
outfile.write(snmp_get)
outfile.write(snmp_set)
outfile.write(timeout)
i += 1
loggermodule.module_logger.debug('Batch File Created: {}'.format(filename))
logger.debug('Batch file created: {}'.format(filename))
def start_batch(self):
try:
global filename
logger.debug('Starting batch file execution')
loggermodule.module_logger.debug('Starting batch file execution')
#s = subprocess.check_output([filename]).decode('utf-8')
process = subprocess.Popen([filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, code = process.communicate()
self.root.update()
''' Logger'''
for line in code.decode('utf-8').splitlines():
if 'Waiting for' not in line:
logger.debug(line)
loggermodule.module_logger.debug(line)
for line in output.decode('utf-8').splitlines():
if 'Waiting for' not in line:
logger.debug(line)
loggermodule.module_logger.debug(line)
loggermodule.module_logger.debug("Batch job completed")
logger.debug("Batch job completed")
# with open(log_file, 'w+') as outfile:
# for line in s.splitlines():
# outfile.write(line)
return self.output
except subprocess.CalledProcessError as e:
logger.exception(e)
loggermodule.module_logger.debug(e)
loggermodule.module_logger.debug("There was an error, Batch file stopped. Check Log file")
'SNMPPage' object has no attribute 'filename'
我希望使用 create_batchfile 创建文件(这是成功的),但是当我运行 start_batchfile 方法时,它失败了,因为 SNMPPage 没有属性“文件名”
【问题讨论】:
-
这个文件名是否必须在所有类实例之间或相同对象方法之间共享?
-
@LiorCohen 实际上只是在两个对象方法之间。一个创建一个批处理文件,另一个运行它。
标签: python-3.x class oop variables global