0

In my current project I'm trying to execute a .sh file with a python program, giving input and reading output The problem is that I have no idea on how to give the input (I managed to read the output in this way, searching on the internet. I'll listen to any suggestion). Here I write an example code (for the original one is longer and more complicated, but this is the essence and the problem is the same)

import subprocess
greet = subprocess.Popen(["bash", "helloWorld.sh"],
                         stdout=subprocess.PIPE,
                         encoding="utf-8")
print(greet.stdout.read())

and this is the simple helloWorld.sh

read name
echo "Hello $name"

My OS is Debian (xfce) and I'm wirting in Python 3.7 Ask for any other detail

  • Did you try `stdin=subprocess.PIPE` as another argument to `Popen`? – GordonAitchJay Mar 13 '20 at 11:11
  • https://stackoverflow.com/questions/17242828/python-subprocess-and-running-a-bash-script-with-multiple-arguments this may help you – Chetan Ameta Mar 13 '20 at 11:15
  • I tried but I don't really know how to use it. Could you write an example? @GordonAitchJay – Matteo_Vezzoli Mar 13 '20 at 11:17
  • 1
    @ChetanAmeta, that's showing command-line arguments, not stdin content. Different thing. – Charles Duffy Mar 13 '20 at 11:22
  • @ChetanAmeta Yes, tried them all (and could't make them work) – Matteo_Vezzoli Mar 13 '20 at 11:23
  • 1
    BTW, ideally you should add a shebang to your `helloWorld` script, take off the `.sh` extension, set the executable permission bit, and just run it with `["./helloWorld"]`. `.sh` extensions imply compatibility with `/bin/sh`, which is a different shell from bash, but in present circumstances there's no reason not to let your script select its own interpreter rather than require its caller to use the right one. – Charles Duffy Mar 13 '20 at 11:24
  • Anyhow, see the linked duplicate -- https://stackoverflow.com/questions/163542/how-do-i-pass-a-string-into-subprocess-popen-using-the-stdin-argument -- it's directly on-point. – Charles Duffy Mar 13 '20 at 11:25
  • @CharlesDuffy I did't find the answer there, but I found out testing that modifying the .sh file (I have yet to do the things you suggested me in the previous comment) to """echo "Hello $1""" and the line in the .py one to """greet = subprocess.Popen(args=["bash", "helloWorld.sh", "name"],""" the output works just fine. – Matteo_Vezzoli Mar 13 '20 at 11:59
  • Right, that's the command-line-argument approach, as given in the answer Chetan linked early on. Better practice, but also not what you asked for. – Charles Duffy Mar 13 '20 at 12:02

0 Answers0