У меня есть код, роль которого заключается в сохранении данных в текстовый файл. У меня также есть функция для очистки файла. К сожалению, после очистки файла данные больше не сохраняются. Я сохраняю вывод iperf.
def start_client_and_print_results(self):
'''Start iperf client and print results to console'''
my_iperf_process = subprocess.Popen([self.initalize_iperf, "-c", self.ip_addr, self.force_flush],stdout=subprocess.PIPE)
for line in my_iperf_process.stdout:
print(line)
self.starting_index_position += 1
if (self.starting_index_position > self.start_line_to_write_into_file and self.starting_index_position < self.end_line):
self.save_results_to_file_txt(str(line) + "\n")
self.save_results_to_file_csv(str(line) + "\n")
Функция, используемая для сохранения данных:
def save_results_to_file_txt(self, output):
'''Save results to a text file'''
client_results = open("client_results.txt", "a")
client_results.write(output)
client_results.close()
Очистите данные с помощью:
def clear_file(self):
clear = open("client_results.txt", "w")
clear.close()
Вышеупомянутые функции используются вместе с библиотекой tkinter, для которой я определил кнопки с соответствующими функциями.
button_iperf = tk.Button(root, text = "Start iperf client", command = iperfing.start_client_and_print_results)
button_clear = tk.Button(root, text = "Clear", command = iperfing.clear_file)
Есть идеи?
Я попробовал использовать оператор with в определении файла, но это не сработало.
Функции определяются в классе.
class Iperf():
'''Class to handle iperf client functionality'''
def __init__(self, initalize_iperf: str, force_flush: str, ip_addr: str, starting_index_position: int, start_line_to_write_into_file: int, end_line: int):
'''Initialize the iperf client instance'''
self.initalize_iperf = initalize_iperf
self.force_flush = force_flush
self.ip_addr = ip_addr
self.starting_index_position = starting_index_position
self.start_line_to_write_into_file = start_line_to_write_into_file
self.end_line = end_line
поэтому полный код выглядит так:
class Iperf():
'''Class to handle iperf client functionality'''
def __init__(self, initalize_iperf: str, force_flush: str, ip_addr: str, starting_index_position: int, start_line_to_write_into_file: int, end_line: int):
'''Initialize the iperf client instance'''
self.initalize_iperf = initalize_iperf
self.force_flush = force_flush
self.ip_addr = ip_addr
self.starting_index_position = starting_index_position
self.start_line_to_write_into_file = start_line_to_write_into_file
self.end_line = end_line
def start_client_and_print_results(self):
'''Start iperf client and print results to console'''
my_iperf_process = subprocess.Popen([self.initalize_iperf, "-c", self.ip_addr, self.force_flush],stdout=subprocess.PIPE)
for line in my_iperf_process.stdout:
print(line)
self.starting_index_position += 1
if (self.starting_index_position > self.start_line_to_write_into_file and self.starting_index_position < self.end_line):
self.save_results_to_file_txt(str(line) + "\n")
self.save_results_to_file_csv(str(line) + "\n")
my_iperf_process.kill()
def start_server(self):
'''Start iperf server'''
my_iperf_process = subprocess.Popen(["iperf3","-s","-B", self.ip_addr, self.force_flush],stdout=subprocess.PIPE)
def save_results_to_file_txt(self, output):
'''Save results to a text file'''
client_results = open("client_results.txt", "a")
client_results.write(output)
client_results.close()
def clear_file(self):
clear = open("client_results.txt", "w")
clear.close()
Я использую эти параметры в классе.
iperf_path = "iperf3"
force_flush = "--forceflush"
ip_addr = "" # Example IP address
starting_index_position = 0
start_line = 3
end_line = 14
Вы видите результат print(line)
? Я не вижу причин, по которым он не записывал бы в файл.
каковы значения self.starting_index_position, self.start_line_to_write_into_file и self.starting_index_position, self.end_line , если (как спрашивает @Barmar - вы видите выходные данные печати) ... являются ли они причиной того, что ничего не сохраняется?
Я добавил класс, который использую, в самом конце поста. Надеюсь, теперь понятно, как это выглядит. Данные отображаются с помощью print() после очистки, но не записываются непосредственно в файл. Позже файл пуст.
Теперь вы также можете увидеть, какие значения я использую в классе.
Хорошо, мне удалось найти обходной путь, который выглядит так. Я не занимаюсь сохранением файлов через Python, а делаю это прямо из терминала:
class Iperf:
'''Class to handle iperf client functionality'''
def __init__(self, initialize_iperf: str, force_flush: str, ip_addr: str, starting_index_position: int, start_line_to_write_into_file: int, end_line: int):
'''Initialize the iperf client instance'''
self.initialize_iperf = initialize_iperf
self.force_flush = force_flush
self.ip_addr = ip_addr
self.starting_index_position = starting_index_position
self.start_line_to_write_into_file = start_line_to_write_into_file
self.end_line = end_line
self.my_iperf_process = None # Hold reference to the subprocess
def start_client_and_print_results(self):
'''Start iperf client and print results to console'''
subprocess.run("iperf3 -c ip-address --forceflush > client_results.txt", shell=True)
def start_server(self):
'''Start iperf server'''
my_iperf_process = subprocess.Popen(["iperf3", "-s", "-B", self.ip_addr, self.force_flush], stdout=subprocess.PIPE)
def clear_file(self):
'''Delete file'''
os.remove("client_results.txt")
# Example usage:
iperf_instance = Iperf("iperf3", "--forceflush", "ip-address", 0, 5, 20)
iperf_instance.start_client_and_print_results()
iperf_instance.clear_file()
iperf_instance.start_client_and_print_results()
Поэтому даже после удаления файла я могу перезаписать его снова. Спасибо всем за ваше время! Возможно, мы найдем и другое решение
Не могли бы вы создать тестируемый минимально воспроизводимый пример? И я не думаю, что iperf там должен быть. Просто окно tkinter с двумя кнопками, которое периодически записывает текст-заполнитель в файл.