Home > front end >  Python program can't find Shellscript File
Python program can't find Shellscript File

Time:09-17

Hey i'm trying to run a shell Script with python using the Following lines:

import subprocess

shellscript = subprocess.Popen(["displaySoftware.sh"], stdin=subprocess.PIPE)

shellscript.stdin.write("yes\n")
shellscript.stdin.close()
returncode = shellscript.wait()

But when I run the Program it says that it can't find the .sh file.

enter image description here

CodePudding user response:

Your command is missing "sh", you have to pass "shell=True" and "yes\n" has to be encoded.

Your sample code should look like this:

import subprocess

shellscript = subprocess.Popen(["sh displaySoftware.sh"], shell=True, stdin=subprocess.PIPE )

shellscript.stdin.write('yes\n'.encode("utf-8"))
shellscript.stdin.close()
returncode = shellscript.wait()

This method might be better:

import subprocess

shellscript = subprocess.Popen(["displaySoftware.sh"], shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
returncode = shellscript.communicate(input='yes\n'.encode())[0]
print(returncode)

When running this on my machine the "displaySoftware.sh" script, that is in the same directory as the python script, is successfully executed.

  • Related