There is a script p = subprocess.Popen('ssh 168.0.0.1 python subscribe.py command', shell=True) it raises the Python script subscribe.py , which returns data endlessly in a loop.

How can we not expect the implementation of the process, the more it is endless, and receive data from it?

1 answer 1

 #!/usr/bin/env python3 import sys from subprocess import Popen, PIPE with Popen([sys.executable, '-u', 'child.py'], stdout=PIPE, universal_newlines=True) as process: for line in process.stdout: print(line.replace('!', '#'), end='') 

child.py:

 #!/usr/bin/env python3 import time for _ in range(5): print('!!!') time.sleep(1) print('Exit. Конец!') 

Console:

 ### ### ### ### ### Exit. Конец# 
  • 1- specify #!/usr/bin/env python3 for source code on Python 3 (as in your example) 2- no coding: utf-8 declaration is required coding: utf-8 in Python 3 use (utf-8 and so the default encoding) 3 - no need to use shell=True (less chance that your code will execute the malicious command). OP can directly call ssh without starting the shell. 4- no need to use stdin=PIPE if you do not write anything to the appropriate pipe. 5- Use universal_newlines=True and print(line, end='') to display the text. 6- Avoid locally Python scripts as subprocess run, better ... - jfs
  • ... [continued] instead import the file as a module and call the appropriate functions. Python script using subprocess 7, it is possible that you still need the -u option to pass to the child python command - otherwise the output to the parent will not be reached in time. - jfs
  • Thanks for the advice, corrected - gil9red
  • 1- universal_newlines = True` turns on text mode in Python 3. If you do not understand the difference between text (Unicode string) and binary data (bytes), see this answer 2- you can use for _ in range(5): to repeat what something five times - jfs
  • still -u not enough to immediately show the output - jfs