0

I have lots of python scripts to be run and I want to automate them. All of them accept inputs at certain times (3 in this case). I have tried something like this but since echo does not have an EOF it did not work:

os.system("echo 4 | echo 5 | echo 6 | python script.py")

I cannot change the content of script.py and it does not accept arguments to it.

How can I automatically input using a line(s) of python code? Thanks.

  • Your shell code simply inputs `6` into the Python script. Piping input to `echo` makes no sense as it ignores its standard input. Probably you mean `printf '%s\n' 4 5 6 | python script.py`. A much better solution is usually to `import script` and run it within your existing script, instead of as a subprocess (though there are scenarios where you do want two processes, such as when you need to be able to interrupt or kill the subprocess from the parent). – tripleee Oct 09 '20 at 12:32

1 Answers1

0

Check out Pexpect:

Pexpect is a pure Python module for spawning child applications; controlling them; and responding to expected patterns in their output. Pexpect works like Don Libes’ Expect. Pexpect allows your script to spawn a child application and control it as if a human were typing commands.

Jussi Nurminen
  • 2,257
  • 1
  • 9
  • 16