running a command line containing Pipes and displaying result to STDOUT

前端 未结 6 977
不思量自难忘°
不思量自难忘° 2020-12-01 06:20

How would one call a shell command from Python which contains a pipe and capture the output?

Suppose the command was something like:

cat file.log |          


        
6条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 06:44

    Simple function for run shell command with many pipes

    Using

    res, err = eval_shell_cmd('pacman -Qii | grep MODIFIED | grep -v UN | cut -f 2')
    

    Function

    import subprocess
    
    
    def eval_shell_cmd(command, debug=False):
        """
        Eval shell command with pipes and return result
        :param command: Shell command
        :param debug: Debug flag
        :return: Result string
        """
        processes = command.split(' | ')
    
        if debug:
            print('Processes:', processes)
    
        for index, value in enumerate(processes):
            args = value.split(' ')
    
            if debug:
                print(index, args)
    
            if index == 0:
                p = subprocess.Popen(args, stdout=subprocess.PIPE)
            else:
                p = subprocess.Popen(args, stdin=p.stdout, stdout=subprocess.PIPE)
    
            if index == len(processes) - 1:
                result, error = p.communicate()
                return result.decode('utf-8'), error
    

提交回复
热议问题