0

Программа запускает cmd команду comp "{path_1}" "{path_2}, а та в свою очередь пишет в stderr (в cmd выводится: Сравнить другие файлы [Y(да)/N(нет)] ?), после чего ожидает ввода информации в stdin со стороны пользователя в cmd. Вопрос: можно ли как-то перенаправить ввод, чтобы автоматически вписывать ответ в консоль без человеческого участия? (попытки print(sys.stdin.write('N')) не привели к желаемому результату)

import os
import sys
import subprocess

def run_command(command):
    process = subprocess.Popen(command, stdin=subprocess.PIPE)
    data = process.communicate()
    for line in data:
        cur_line = line.encode('cp1251').decode("cp866")
        if 'Не удается найти или открыть' in cur_line:
            print(sys.stdin.write('N'))
        elif 'Различия не найдены' in cur_line:
            continue
        else:
            print(cur_line)


command = "dir /B /S /AD"
dirs_inside = [line.encode('cp1251').decode("cp866") for line in os.popen(command)]
for dir_ in enumerate(dirs_inside):
    dirs_inside[dir_[0]] = dir_[1][:-1]
cur_dir = os.getcwd()
all_dirs = [cur_dir] + dirs_inside

disk = 'H'
command_template = 'comp "{path_1}" "{path_2}"'
for dir_ in all_dirs:
    path1 = disk + dir_[1:]
    path2 = dir_
cur_command = command_template.format(path_1=path1, path_2=path2)
print(cur_command)
run_command(['comp', path1, path2])

1 ответ 1

0

Попробуйте так:

out, err = process.communicate(input='N', timeout=3)

Вот в документации подробней. Насчет попытки sys.stdin.write() есть такое предупреждение:

Warning Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.