Python subprocess readlines()?

后端 未结 5 1538
小蘑菇
小蘑菇 2021-01-01 16:46

So I\'m trying to move away from os.popen to subprocess.popen as recommended by the user guide. The only trouble I\'m having is I can\'t seem to find a way of making readli

相关标签:
5条回答
  • 2021-01-01 17:06
    list = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE).communicate()[0].splitlines()
    

    straight from the help(subprocess)

    0 讨论(0)
  • 2021-01-01 17:13

    A more detailed way of using subprocess.

            # Set the command
            command = "ls -l"
    
            # Setup the module object
            proc = subprocess.Popen(command,
                                shell=True,   
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
    
            # Communicate the command   
            stdout_value,stderr_value = proc.communicate()
    
            # Once you have a valid response, split the return output    
            if stdout_value:
                stdout_value = stdout_value.split()
    
    0 讨论(0)
  • 2021-01-01 17:15

    Making a system call that returns the stdout output as a string:

    lines = subprocess.check_output(['ls', '-l']).splitlines()
    
    0 讨论(0)
  • 2021-01-01 17:20
    ls = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE)
    out = ls.stdout.readlines()
    

    or, if you want to read line-by-line (maybe the other process is more intensive than ls):

    for ln in ls.stdout:
        # whatever
    
    0 讨论(0)
  • 2021-01-01 17:30

    With subprocess.Popen, use communicate to read and write data:

    out, err = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE).communicate() 
    

    Then you can always split the string from the processes' stdout with splitlines().

    out = out.splitlines()
    
    0 讨论(0)
提交回复
热议问题