How to give a command line command from python?

This question already has an answer here:

  • Calling an external command in Python 50 answers
  • Executing command line programs from within python [duplicate] 5 answers

  • Use subprocess

    example:

    >>> subprocess.call(["ls", "-l"])
    0
    
    >>> subprocess.call("exit 1", shell=True)
    1
    

    With subprocess one can conveniently perform command-line commands and retrieve the output or whether an error occurred:

    import subprocess
    def external_command(cmd): 
        process = subprocess.Popen(cmd.split(' '),
                               stdout=subprocess.PIPE, 
                               stderr=subprocess.PIPE)
    
        # wait for the process to terminate
        out, err = process.communicate()
        errcode = process.returncode
    
        return errcode, out, err
    

    Example:

    print external_command('ls -l')
    

    It should be no problem to rearrange the return values.

    链接地址: http://www.djcxy.com/p/13504.html

    上一篇: 在Python中捕获netcat shell命令输出

    下一篇: 如何从python提供命令行命令?