将变量发送到另一个函数的问题

时间:2019-12-19 01:31:13

标签: python

  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)

提前谢谢!

1 个答案:

答案 0 :(得分:0)

您需要将返回的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)