3

So I am trying to do something like this:

f = io.StringIO("Hello World!\nI am a banana!\n")
p = subprocess.run(['./temp.out'],
                   stdin=f,
                   capture_output=True,text=True)
print(p.stdout)

This however gets the following error:

---------------------------------------------------------------------------

UnsupportedOperation                      Traceback (most recent call last)

<ipython-input-35-92615c4bbadd> in <module>()
      2 p = subprocess.run(['./temp.out'],
      3                    stdin=f,
----> 4                    capture_output=True,text=True)
      5 p.stdout

2 frames

/usr/lib/python3.7/subprocess.py in run(input, capture_output, timeout, check, *popenargs, **kwargs)
    486         kwargs['stderr'] = PIPE
    487 
--> 488     with Popen(*popenargs, **kwargs) as process:
    489         try:
    490             stdout, stderr = process.communicate(input, timeout=timeout)

/usr/lib/python3.7/subprocess.py in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags, restore_signals, start_new_session, pass_fds, encoding, errors, text)
    751         (p2cread, p2cwrite,
    752          c2pread, c2pwrite,
--> 753          errread, errwrite) = self._get_handles(stdin, stdout, stderr)
    754 
    755         # We wrap OS handles *before* launching the child, otherwise a

/usr/lib/python3.7/subprocess.py in _get_handles(self, stdin, stdout, stderr)
   1374             else:
   1375                 # Assuming file-like object
-> 1376                 p2cread = stdin.fileno()
   1377 
   1378             if stdout is None:

UnsupportedOperation: fileno

Or in other words I want a way to pass a python string as 'seekable' stream to a subprocess. This would be something similar to this in bash:

temp.out < inputfile

Only instead of inputfile being a file, I want it to be a string. Note that passing the string using the input argument doesn't work because then stdin in the subprocess is not seekable.

Can this be done without creating files explicitly? Or is that the only way to do it?

Siam Habib
  • 33
  • 2
  • See this question: [How do I pass a string into subprocess.Popen (using the stdin argument)?](https://stackoverflow.com/questions/163542/how-do-i-pass-a-string-into-subprocess-popen-using-the-stdin-argument) and [this interesting answer to another question](https://stackoverflow.com/questions/48752152/how-do-i-pass-a-string-in-to-subprocess-run-using-stdin-in-python-3/59496029#59496029) using subprocess.run. – Adrien Aug 19 '22 at 08:57

0 Answers0