Test: Python invokes the cmd command three ways

Source: Internet
Author: User

目前我使用到的python中执行cmd的方式有三种
Using Os.system ("cmd")
    该方法在调用完shell脚本后,返回一个16位的二进制数,低位为杀死所调用脚本的信号号码,高位为脚本的退出状态码,即脚本中“exit 1”的代码执行后,os.system函数返回值的高位数则是1,如果低位数是0的情况下,则函数的返回值是0×100,换算为10进制得到256。 如果我们需要获得os.system的正确返回值,那使用位移运算可以还原返回值: >>> n = os.system(test.sh) >>> n >> 8 >>> 3 这是最简单的一种方法,特点是执行的时候程序会打出cmd在linux上执行的信息。使用前需要import os。 os.system("ls") 仅仅在一个子终端运行系统命令, 而不能获取命令执行后的返回信息
Os. Popen
    这种调用方式是通过管道的方式来实现,函数返回一个file-like的对象,里面的内容是脚本输出的内容(可简单理解为echo输出的内容)。使用os.popen调用test.sh的情况:python调用Shell脚本,有两种方法:os.system(cmd)或os.popen(cmd),前者返回值是脚本的退出状态码,后者的返回值是脚本执行过程中的输出内容。实际使用时视需求情况而选择。明显地,像调用”ls”这样的shell命令,应该使用popen的方法来获得内容    popen(command [, mode=‘r‘ [, bufsize]]) -> pipe    tmp = os.popen(‘ls *.py‘).readlines()
Subprocess. Popen
Most people now like to use Popen. The Popen method does not print out the information that CMD executes on Linux. Indeed, Popen is very powerful and supports a variety of parameters and patterns. Need from subprocess import Popen, PIPE before use. But there is a flaw in the Popen function, which is that it is a blocking method. If there is a lot of content generated when you run CMD, the function is very easy to block.        The workaround is not to use the wait () method, but you cannot get the return value of the execution. The Popen prototype is: subprocess. Popen (args, bufsize=0, Executable=none,Stdin=none,Stdout=none,Stderr=none, Preexec_fn=none, Close_fds=false, shell=false) parameter bufsize: Specifies the buffer. I still do not know the specific meaning of this parameter, look at each Daniel pointing. The parameter executable is used to specify the executable program. In general, we use the args parameter to set the program to run. If you set the parameter shell to true,executable, the shell will be used by the specified program. Under the Windows platform, the default shell is specified by the COMSPEC environment variable. ParametersStdinStdOutThe stderr represents the standard input, output, and error handles of the program, respectively. They can be pipe, file descriptor or file object, or set to none, which means inheriting from the parent process. The parameter PREEXEC_FN is only valid on UNIX platforms and is used to specify an executable object (callable object) that will be called before the child process runs. Parameter CLOSE_SFS: Under the Windows platform, if Close_fds is set to true, the newly created child process will not inherit the input, output, and error pipes of the parent process. We cannot set Close_fds to true while redirecting the standard input, output, and error of the child process (StdinStdOutSTDERR). If the parameter shell is set toTrue, the program executes through the shell. The parameter CWD is used to set the current directory of the child process. The parameter env is a dictionary type that specifies the environment variables for the child process. If env = None, the environment variables of the child process are inherited from the parent process. Parameter universal_newlines: Under different operating systems, text line breaks are not the same. such as: Under Windows with '/r/n ' for Exchange, and Linux under the '/n '. If this parameter is set to True,python uniform, these newline characters are treated as '/n '. Parameters Startupinfo and Createionflags are only used under Windows, and they are passed to the underlying CreateProcess () function to set some properties of the child process, such as the appearance of the main window, the priority of the process, and so on. Subprocess. PIPE when creating a Popen object, subprocess. Pipe can be initializedStdinStdOut orThe stderr parameter that represents the standard stream that communicates with the child process. Subprocess. STDOUT when you create a Popen object, you use it to initializeThe stderr parameter indicates that errors are output through the standard output stream. Popen method: Popen.poll () is used to check whether the child process has ended. Sets and returns the ReturnCode property. Popen.wait () Waits for the child process to end. Sets and returns the ReturnCode property. Popen.communicate (Input=none) interacts with the child process. Tostdin send data, or fromStdOut andThe data is read in the stderr. Optional parameter input Specifies the parameters that are sent to the child process. Communicate () returns a tuple: (Stdoutdata, Stderrdata). Note: If you want to pass the process'sStdIn sends the data to it, when creating the Popen object, the parametersStdIn must be set to pipe. Similarly, if you want tostdout and stderr get the data, the stdout and stderr must be set to pipe. Popen.send_signal (signal) sends a signal to the child process. Popen.terminate () Stop (stop) child process. Under the Windows platform, this method will call Windows API TerminateProcess () to end the child process. Popen.kill () kills the child process. Popen. stdin If the Popen object is created, the parameter stdin is set to Pipe,popen.  StdIn will return a file object for the policy sub-process send instruction. Otherwise, none is returned. Popen. stdout If the Popen object is created, the parameter stdout is set to Pipe,popen.  STDOUT will return a file object for the policy sub-process send instruction. Otherwise, None is returned. Popen. stderr If the Popen object is created, the parameter stdout is set to Pipe,popen.  STDOUT will return a file object for the policy sub-process send instruction. Otherwise, None is returned. Popen.pid Gets the process ID of the child process. Popen.returncode gets the return value of the process. Returns none if the process is not finished yet. 
Example of a
= Popen("cp -rf a/* b/", shell=True, stdout=PIPE, stderr=PIPE) p.wait() if p.returncode != 0: print "Error." return -1 
Using the Commands.getstatusoutput method
    这个方法也不会打印出cmd在linux上执行的信息。这个方法唯一的优点是,它不是一个阻塞的方法。即没有Popen函数阻塞的问题。使用前需要import commands。
Like what
    output = commands.getstatusoutput("ls")      还有只获得output和status的方法:    commands.getoutput("ls")      commands.getstatus("ls")

Test: Python invokes the cmd command three ways

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.