Redirecting stdio from a command in os.system() in Python

前端 未结 4 624
一向
一向 2020-11-30 10:36

Usually I can change stdout in Python by changing the value of sys.stdout. However, this only seems to affect print statements. So, is there any

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 11:28

    You could consider running the program via subprocess.Popen, with subprocess.PIPE communication, and then shove that output where ever you would like, but as is, os.system just runs the command, and nothing else.

    from subprocess import Popen, PIPE
    
    p = Popen(['command', 'and', 'args'], stdout=PIPE, stderr=PIPE, stdin=PIPE)
    
    output = p.stdout.read()
    p.stdin.write(input)
    

    Much more flexible in my opinion. You might want to look at the full documentation: Python Subprocess module

提交回复
热议问题