Reputation: 79
I'm trying to automate the deletion of a program with python and shell scripts. this is the code I use to execute my shell scripts.
import subprocess
self.shellscript = subprocess.Popen([self.shellScriptPath], shell=True, stdin=subprocess.PIPE )
self.shellscript.stdin.write('yes\n'.encode("utf-8"))
self.shellscript.stdin.close()
self.returncode = self.shellscript.wait()
This is the shell script that I want to run.
echo *MY PASSWORD* | sudo -S apt-get --purge remove *PROGRAM*
echo *MY PASSWORD* | sudo -S apt-get autoremove
echo *MY PASSWORD* | sudo -S apt-get clean
I know it's not secure to code my password into it like this but I will fix this later.
My problem is that the commandline asks me to type y/n
but the program skips that and nothing happens.
Upvotes: 0
Views: 207
Reputation: 189397
In this particular case, the absolutely simplest fix is to use
apt-get -y ...
and do away with passing input to the command entirely.
In the general case, you want to avoid Popen
in every scenario where you can. You are reimplementing subprocess.call()
but not doing it completely. Your entire attempt can be reduced to (and fixed with)
self.returncode = subprocess.run(
self.shellScriptPath, input='yes\n', text=True).returncode
Unless the commands in self.shellScriptPath
require a shell, probably remove shell=True
and, if necessary, shlex.split()
the value into a list of tokens (though if it's already a single token, just split it yourself, trivially: [self.shellScriptPath]
).
Upvotes: 1