import subprocess# executes the command, returns the command execution status , 0 or non-0retcode = subprocess.call (["Free", "-M"]) #返回值可判断执行是否正确, the command execution results are returned directly to the screen # Execution command, if the command result is 0, return normally, otherwise throw exception result = Subprocess.check_call (["LS", "-l"]) #执行命令 and returns the result, note that the result is returned, not printed, and the following example returns to Resres = subprocess.check_output ([ "LS", "-l"]) #若shell = true, The shell parameter is given as a string, otherwise, the #python3 executes the shell command in the form of a sequence # #. Os.system (cmd) can get the return value after the command executes, but cannot get the output content of the command Import os;return_code=os.system (' Ls -la ' );p rint (Return_code), #2. Os.popen (cmd) can get the output of the command, but cannot get the return value after the command executes import os;import Sys;output=os.popen (' ls -l '); Out=output.readlines ();for i in out: Print (I.strip ()); #3. With subprocessimport os;import sys;import subprocess;import codecs;# The output can be written directly to the file Output_file=codecs.open (' Abc.txt ', ' w ', ' utf-8 '); Return_code=subprocess.call ([' ls ', '-l '],stdout= output_file); Output_file.close ();p RINT (Return_code); #也可以先将输出先保存为string变量, output=subprocess.check_output ([' ls ', '-l ']); # If the return value of the command execution is not 0, the Calledprocesserror error print (Output.decode (' Utf-8 ')) is thrown, and the #再将string变量写入到文件output_file =codecs.open (' Abc.txt ', ' w ', ' utf-8 '); Output_file.write (Output.decode (' utf-8 ')); Output_file.close ();
This article is from the "Eight Miles" blog, so be sure to keep this source http://5921271.blog.51cto.com/5911271/1897550
Python path 35-subprocess modules and Python3 common execution shell command methods