Python Forum
re-open a Popen pipe in non-binary mode
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
re-open a Popen pipe in non-binary mode
#2
You can reuse the already opened Pipe.

Here two different approaches:

import os
import subprocess
import io

# Low Level approach
proc = subprocess.Popen(['cat'], stdin=subprocess.PIPE)
proc.stdin.fileno()
tw = os.fdopen(proc.stdin.fileno(), 'w', encoding='utf8')
tw.write('Hello World\n')
tw.flush()
proc.stdin.write(b'Hello World bytes\n')
proc.stdin.flush()
proc.stdin.close()

# tw is now also closed.

# different approach with io
proc = subprocess.Popen(['cat'], stdin=subprocess.PIPE)
tw2 = io.TextIOWrapper(proc.stdin, encoding='utf8')
tw2.write('Hello ...\n')
tw2.flush()
proc.stdin.write(b'Bin ...\n')
proc.stdin.flush()

tw2.close()
# will close also proc.stdin
The command cat reads from stdin.
It prints the data on the screen, when the pipe stdin was closed.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: re-open a Popen pipe in non-binary mode - by DeaD_EyE - Jul-29-2019, 09:36 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  which exception do you get when you os.write() to a pipe that has nothing reading it? Skaperen 7 3,436 Jan-09-2023, 09:45 AM
Last Post: Gribouillis
  pipe(s) in = subprocess.Popen() Skaperen 0 2,336 Feb-13-2021, 11:48 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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