Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python subprocess.Popen pipe custom fd

I currently have this code that pipe stdout or stderr following the context:

def execteInstruction(cmd, outputNumber):
  do_stdout = DEVNULL
  do_stderr = DEVNULL
  if outputNumber != 2:
    do_stdout = subprocess.PIPE
  else:
    do_stderr = subprocess.PIPE
  return subprocess.Popen(cmd, shell=True, stderr=do_stderr, stdout=do_stdout)

And then I read the result with communicate(). This works perfectly well except that I need to read a custom fd because I'm using subprocess to run a command that output on the file descriptor 26.

I have seen code that write to another fd than stdout or stderr, but none that read from a custom fd. So how can I pipe a custom fd from subprocess.Popen ?

like image 972
Papotitu Avatar asked Feb 12 '26 17:02

Papotitu


1 Answers

Since I needed an answer to this, here's a much belated answer for others:

To implement a similar use of additional fds in Python, I came up with this code:

import os, subprocess

read_pipe, write_pipe = os.pipe()
xproc = subprocess.Popen(['Xephyr', '-displayfd', str(write_pipe)],
                         pass_fds=[write_pipe])

display = os.read(read_pipe, 128).strip()

I think os.dup2(write_pipe, 26) before the Popen constructor combined with pass_fds=[26] would do that last step of getting you a specific fd number, rather than just whatever os.pipe chose, but I haven't tested it.

If nothing else, it should be possible to redirect fd 26 to whatever write_pipe turns out to be if you use subprocess.Popen to call a shell-script wrapper which runs exec 26>$WHATEVER before calling the actual target command.

like image 71
ssokolow Avatar answered Feb 15 '26 11:02

ssokolow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!