首页 > 解决方案 > 将变量发送到另一个函数的问题

问题描述

  1. 调用函数什么检查文件内容、大小等
  2. 如果文件被文件大小更改,则调用函数,如果文件大小更改检查文件内容,将更改添加到列表或从列表中删除问题如何在其他函数中正确使用变量?
import re
import os
from time import sleep

hosts_file = "hosts.txt"

class Hosts(object):

    def __init__(self):
        self.hosts_file = hosts_file

    def get_file_size(self):
        f_size = os.stat(self.hosts_file)
        return f_size.st_size

def work_with_hosts_file():
    host_file_work = Hosts()
    file_size = host_file_work.get_file_size()
    return file_size # use this var

def compare_hosts_file_size(): # in this function
    host_file_work = Hosts()
    file_size_check = host_file_work.get_file_size()
    if file_size != file_size_check:
        #do stuff        

if __name__ == "__main__":
    work_with_hosts_file()
    get_connection_hosts_info()
    while True:
        compare_hosts_file_size()
        sleep(5.0)

先感谢您!

标签: python

解决方案


您需要将 的返回值分配work_with_hosts_file()给一个变量,然后将其作为参数传递给compare_hosts_file_size().

import re
import os
from time import sleep

hosts_file = "hosts.txt"

class Hosts(object):

    def __init__(self):
        self.hosts_file = hosts_file

    def get_file_size(self):
        f_size = os.stat(self.hosts_file)
        return f_size.st_size

def work_with_hosts_file():
    host_file_work = Hosts()
    file_size = host_file_work.get_file_size()
    return file_size # use this var

def compare_hosts_file_size(file_size): # in this function
    host_file_work = Hosts()
    file_size_check = host_file_work.get_file_size()
    if file_size != file_size_check:
        #do stuff        

if __name__ == "__main__":
    size = work_with_hosts_file()
    get_connection_hosts_info()
    while True:
        compare_hosts_file_size(size)
        sleep(5.0)

推荐阅读