How to call a shell script from python code?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- How to get the return code of a shell script in lu
- Evil ctypes hack in python
There are some ways using
os.popen()
(deprecated) or the wholesubprocess
module, but this approachis one of the easiest.
I'm running python 3.5 and subprocess.call(['./test.sh']) doesn't work for me.
I give you three solutions depends on what you wanna do with the output.
1 - call script. You will see output in your terminal. output is a number.
2 - call and dump execution and error into string. You don't see execution in your terminal unless you print(stdout). Shell=True as argument in Popen doesn't work for me.
3 - call script and dump the echo commands of temp.txt in temp_file
Don't forget to take a look at the doc subprocess
In case you want to pass some parameters to your shell script, you can use the method shlex.split():
with
test.sh
in the same folder:Outputs:
Subprocess module is a good module to launch subprocesses. You can use it to call shell commands as this:
You can see its documentation here.
If you have your script written in some .sh file or a long string, then you can use os.system module. It is fairly simple and easy to call:
This command will run the script once, to completion, and block until it exits.