The system method creates a child process to run the external program, and the method returns only the results of running the external program. This method is better suited for situations where the external program has no output.
import os ('ls')
Use the getoutput method of the commands module, the difference between this method and popend is that popen returns a file handle, while this method returns the output of the external program as a string, which is more convenient in many cases.
Main methods.
- (cmd) return(status, output)
- (cmd) Returns only the output
- (file) Returns the result string of the execution of ls -ld file, which is not recommended if getoutput is called.
This method is useful when you need to get the output of an external program. For example, when calling the Web API using urllib, you need to process the data you get. (cmd) To get the output of a command, simply call read() or readlines() again, etc. e.g. a=(cmd).read()
import os ls = ('ls') print ()
Use the getoutput method of the commands module, the difference between this method and popend is that popen returns a file handle, while this method returns the output of the external program as a string, which is more convenient in many cases.
Main methods.
- (cmd) return(status, output)
- (cmd) Returns only the output
- (file) Returns the result string of the execution of ls -ld file, which is not recommended if getoutput is called.
import commands ('ls -lt') # come (or go) back(status, output)
According to the official Python documentation, the subprocess module is used to replace these modules. There is a parallel ssh tool implemented in Python - mssh, the code is very short but interesting, it calls subprocess in the thread to start a sub-process to do the work.
from subprocess import call call(["ls", "-l"])
import shlex, subprocess def shell_command(cmd, timeout) : data = {"rc":False, "timeout":False, "stdout":"", "stderr":""} try : process = (cmd, shell=True, stdout=, stderr=) try: outs, errs = (timeout=timeout) data["stdout"] = ("utf-8") data["stderr"] = ("utf-8") data["rc"] = True except : () outs, errs = () data["rc"] = False data["stdout"] = ("utf-8") data["stderr"] = "timeout" data["timeout"] = True except Exception as e : data["rc"] = False data["stderr"] = e finally : return data
To this point this article on python shell execution knowledge points of the article is introduced to this, more related python shell execution content please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!