Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
-
subprocess.run
is preferred to the functionos.system
for invoking shell commands. For more discussions, pleaser refer to [Hands on the Python module subprocess]https://www.legendu.net/en/blog/hands-on-the-python-model-subprocess . -
There are multiple ways to feed input to a shell command programmatically instead of interactively via stdin.
-
Pipe is used to feed the output (text) of a shell command as the input to another shell command. What if you have something that is not the output a shell command? A simple trick is to echo it and feed it to the shell command. The command below is an example of feeding password to the shell command
kinit
.echo 'your_password' | kinit
-
The above trick can be used both for
os.system
andsubprocess.run
(withshell=True
). However,subprocess.run
has an better built-in support to feed input to a shell command via theinput
parameter.subprocess.run(["kinit"], input=b"your_password")
-
pexpect
-
shlex
Parsing Shell commands.
References
https://docs.python.org/3/library/subprocess.html