этот код не работает import os import multiprocessing def search_lines(lines, inp,…
- User
этот код не работает
import os import multiprocessing
def search_lines(lines, inp, result): found = False for line in lines: if inp.lower() in line.lower(): result.append(line) result.append("-" * 90) found = True if not found: result.append('Ничего не найдено!')
folder_path = "./" directories = [name for name in os.listdir(folder_path) if os.path.isdir(os.path.join(folder_path, name))]
print("Выберите папку:") for i, directory in enumerate(directories, 1): print(f"{i}. {directory}")
selected_index = input("Введите номер выбранной папки: ") selected_index = int(selected_index) - 1
if selected_index >= 0 and selected_index < len(directories): selected_folder = directories[selected_index] files = os.listdir(selected_folder) else: print("Недопустимый номер папки!")
selected_folder = directories[selected_index] files = os.listdir(selected_folder)
…
l = [] for filename in files: print('Загрузка…', filename) file_path = os.path.join(selected_folder, filename) with open(file_path, 'r', encoding="utf-8") as file: all_lines = file.read() l.extend(all_lines.split("\n"))
lines = l if name == 'main': while True: print("" * 90) print('Структура базы: ', selected_folder) print("" * 90) print(lines[5]) print("*" * 90) inp = input('Поиск:')
result = [] processes = [] num_processes = multiprocessing.cpu_count() for i in range(num_processes): num_lines = len(lines) start = num_lines // num_processes * i end = num_lines // num_processes * (i + 1) if i < num_processes - 1 else num_lines sub_lines = lines[start:end] process = multiprocessing.Process(target=search_lines, args=(sub_lines, inp, result)) processes.append(process) process.start() for process in processes: process.join() for line in result: print(line) - Assistant
Could you please provide more information about the issue you are facing with this code? Are you receiving any error messages?
- User
ошибок нет но код не делает поиск введенных данных в списке
- Assistant
I see. Upon reviewing the code, it appears that the issue lies in the
search_lines()function. The function loops through each line in thelineslist and checks if the input string is present in that line. However, instead of appending the line itself to theresultlist, the code appends the entirelineobject.To correct this issue, you can modify the
search_lines()function as follows:def search_lines(lines, inp, result): found = False for line in lines: if inp.lower() in line.lower(): result.append(line) # Append the line itself, not the line object result.append("-" * 90) found = True if not found: result.append('Ничего не найдено!')With this modification, the function will append the actual line that contains the input string to the
resultlist.Additionally, you can change the line
print("" * 90)toprint(" " * 90)in order to print 90 empty spaces.Please try making these changes and see if it resolves the issue with the code.
- User
line 122, in spawn_main exitcode = _main(fd, parent_sentinel) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\1\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 131, in _main prepare(preparation_data) File "C:\Users\1\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 246, in prepare _fixup_main_from_path(data['init_main_from_path']) File "C:\Users\1\AppData\Local\Programs\Python\Python311\Lib\multiprocessing\spawn.py", line 297, in _fixup_main_from_path main_content = runpy.run_path(main_path, ^^^^^^^^^^^^^^^^^^^^^^^^^
- Assistant
The error message suggests that there is an issue with the
run_path()function from therunpymodule. It seems like the multiprocessing package in Python 3.11 is encountering an error when trying to execute the target function in a separate process.One possible solution is to guard the main code execution with the following block:
if __name__ == "__main__": # Your code hereBy adding this block, you ensure that the main code will only be executed when the script is run directly and not when it is imported as a module. This can help avoid any conflicts with the multiprocessing package.
Here's an updated version of the code with the suggested modification:
import os import multiprocessing # ... if __name__ == "__main__": l = [] for filename in files: print('Загрузка…', filename) file_path = os.path.join(selected_folder, filename) with open(file_path, 'r', encoding="utf-8") as file: all_lines = file.read() l.extend(all_lines.split("\n")) lines = l while True: # ...Please try this modification and see if it resolves the issue with the code.