How to hide output of subprocess in Python 2.7

前端 未结 5 1175
无人及你
无人及你 2020-11-22 01:14

I\'m using eSpeak on Ubuntu and have a Python 2.7 script that prints and speaks a message:

import subprocess
text = \'Hello World.\'
print text
subprocess.ca         


        
5条回答
  •  广开言路
    2020-11-22 02:02

    Redirect the output to DEVNULL:

    import os
    import subprocess
    
    FNULL = open(os.devnull, 'w')
    retcode = subprocess.call(['echo', 'foo'], 
        stdout=FNULL, 
        stderr=subprocess.STDOUT)
    

    It is effectively the same as running this shell command:

    retcode = os.system("echo 'foo' &> /dev/null")
    

    Update: This answer applies to the original question relating to python 2.7. As of python >= 3.3 an official subprocess.DEVNULL symbol was added.

    retcode = subprocess.call(['echo', 'foo'], 
        stdout=subprocess.DEVNULL, 
        stderr=subprocess.STDOUT)
    

提交回复
热议问题