Код
pexpect_test.py
Код: Выделить всё
if __name__ == '__main__':
count = 3
processes = []
for x in range(count):
processes.append(pexpect.spawn('/bin/bash', logfile=sys.stdout.buffer))
print(f'Processes Created: {len(processes)}')
inputs = ['a', 'b', 'c']
for input in inputs:
print(f'Processing input: {input}')
for process in processes:
line = f'python test.py {input}'
print(f'Sending Line: {line}')
process.sendline(line)
print('reading')
res = process.read()
print(f'res: {res}')
Код: Выделить всё
if __name__ == '__main__':
print(f'Process Started: {argv[1]} ')
sleep(2)
print(f'Process Complete: {argv[1]}')
Код: Выделить всё
$ python pexpect_test.py
Processes Created: 3
Processing input: a
Sending Line: python x.py a
python x.py a
reading
$ python x.py a
Process Started: a
Process Complete: a
$ ^CTraceback (most recent call last):
Код: Выделить всё
cУпрощенный пример
Код: Выделить всё
if __name__ == '__main__':
ps = pexpect.spawn('/bin/bash', logfile=sys.stdout.buffer)
ps.sendline('python x.py 1 a')
# Expect EOF
ps.expect(pexpect.EOF)
# - The child bash shell stays active and control does not go back to python code
# - Will eventully timeout as expected and raise an exception
# - Does correctly call python script and waits for the defined amount of time
# Expect terminal character
ps.expect_exact('$ ')
# - The wait is skipped but the child shell does not remain active
# Expect literal string printed in child process
ps.expect_exact('Completed')
# - Correctly spawns child thread and waits specified duration
# - Return control back to script
# - The requirement to add a print statement containing unique string is not desirable.
# -There could be hundreds of different processes that need to be run and my group does not manage their code.
# Expect the terminal character twice
ps.expect('\$.*\$ ')
# - For some reason this works exactly as I need it to.
[*]Используйте subprocess.run(...): недостаточно производительно. В приведенном выше примере кода в качестве заполнителя используется bin/bash, инициализация фактической команды, которую мне нужно выполнить, занимает 2–3 секунды, и мне нужно обработать много входных данных (10000+).
Подробнее здесь: https://stackoverflow.com/questions/791 ... shell-open
Мобильная версия