Search code examples
pythonpython-3.xsubprocesspopenfile-descriptor

How to access subprocess Popen pass_fds argument from subprocess?


So the title is a bit long but it is the only thing I cannot find online, with a little bit searching. How do I access the pass_fds argument from subprocess?

# parent.py
import subprocess

subprocess.Popen(['run', 'some', 'program'], pass_fds=(afd, bfd))

# child.py
import subprocess

# need to access pass_fds argument? but how?

Solution

  • You need to explicitly inform the child of the fds passed in some way. The most common/simple mechanisms would be:

    1. Via an environment variable set for the child
    2. Via an argument passed to the child
    3. (Less common, but possible) Written to the child's stdin

    All of these require the child's cooperation of course; it needs to define an interface to inform it of the fds passed.

    openssl's command line tool supports all these mechanisms for a similar purpose (communicating a passphrase to the child without putting it on the command line). You pass -pass and a second argument that defines where to look for the password. If the second argument is stdin, it reads from stdin, if it's -pass fd:# (where # is the fd number) it reads from an arbitrary file descriptor provided, -pass env:var (where var is the name of an environment variable) reads from the environment, etc.