running a command line containing Pipes and displaying result to STDOUT

前端 未结 6 971
不思量自难忘°
不思量自难忘° 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条回答
  •  Happy的楠姐
    2020-12-01 06:39

    This:

    import subprocess
    p = subprocess.Popen("cat file.log | tail -1", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    #for shell=False use absolute paths
    p_stdout = p.stdout.read()
    p_stderr = p.stderr.read()
    print p_stdout
    

    Or this should work:

    import os
    result = os.system("cat file.log | tail -1")
    

提交回复
热议问题