Python Forum
printing interleaved lines from many processes
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
printing interleaved lines from many processes
#3
To ensure that the long lines of info printed by child processes are not broken in the middle when redirected by the shell, you can utilize the subprocess module in Python. Specifically, you can use subprocess.Popen to launch the child processes and handle their output.

Here's a basic approach:

Use subprocess.Popen to launch the child processes.
Redirect the stdout of each child process to a pipe.
Read from the pipe in the parent process and print the output.
Here's a simplified example:

python
Copy code
import subprocess

# Launch child process with stdout redirected to a pipe
child_process = subprocess.Popen(['your_child_process_command'], stdout=subprocess.PIPE)

# Read output from the child process line by line
for line in child_process.stdout:
# Print the line without breaking in the middle
print(line.decode('utf-8').rstrip()) # Decode from bytes to string and remove trailing newline
This approach ensures that each line of output from the child process is printed in its entirety, without being broken in the middle, even when redirected by the shell. It also handles Unicode characters encoded in UTF-8 format properly.

You can extend this basic approach to handle multiple child processes by launching them sequentially or in parallel, depending on your requirements. Additionally, you may need to handle error handling and other considerations depending on the specific behavior of your child processes and the environment they are running in.
Reply


Messages In This Thread
RE: printing interleaved lines from many processes - by wearsafe - Feb-20-2024, 01:48 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  launch processes from threads Skaperen 9 994 Feb-21-2024, 01:16 AM
Last Post: Skaperen
  order to call Popen for 2 piped processes Skaperen 0 1,203 Oct-22-2020, 11:31 PM
Last Post: Skaperen
  capture stdout from child processes Skaperen 0 3,363 Oct-30-2019, 12:11 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020