0
import subprocess

x = subprocess.Popen('/home/test/.local/share/somebinary arg1 arg2',
                 shell=True,
                 stdout=subprocess.PIPE,
                 stdin=subprocess.PIPE,
                 stderr=subprocess.PIPE)

x.stdin.write(b'user input')

x.communicate(input=b'\n')

I tried stdin.write and communicate but none of these things enter input in the process after executing initial command mentioned in Popen().

This is the output I get for above code:

$ python test.py

enter user input:

Process expects an input at this point and nothing happens until I manually write something or press enter.

Expected output:

$ python test.py

enter user input:user input
$

I tried the code from selected answer in How do I pass a string into subprocess.Popen (using the stdin argument)? and it does not resolve the issue. I get the same result.

  • Does this answer your 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) – PApostol May 30 '22 at 20:16
  • @PApostol I tried it but same result so it does not answer my question. –  May 30 '22 at 20:28
  • Why not simply use python's builtin `input()`? Is your actual use case more complicated than your example? – Håken Lid May 30 '22 at 20:34
  • 1
    @HåkenLid I assume the process requiring input is not a Python program, but rather some other program being run from within Python using subprocess.Popen(). The issue is not with getting input from user -> python but rather from python -> new process – Esther May 30 '22 at 20:36
  • Exactly. So they could use `input()` in the parent process to get the user input, and then pass it the sub process. – Håken Lid May 30 '22 at 20:46
  • @HåkenLid `input('\n')`results in enter key after or before the place where it is required. It does not fix the issue. Just adds more input in the terminal. –  May 30 '22 at 21:33

1 Answers1

0

This resolved the issue:

import pexpect
child = pexpect.spawn ('/home/test/.local/share/somebinary arg1 arg2')
child.expect ('enter user input:')
child.sendline ('user input/n')
print(child.before)
child.interact()

It is based on https://stackoverflow.com/a/66754162/18991902

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 31 '22 at 00:48