pythonbasherror-handlingsystemsubprocess

Python: os.system() without return or error


I need to use os.system() a few times in my script, but I don't want errors from the shell to appear in my script's window. Is there a way to do this? I guess it's sort of like silent commands, running to their full extent, but not returning any text. I can't use 'try', because it's not a Python error.


Solution

  • You could redirect the command's standard error away from the terminal. For example:

    # without redirect
    In [2]: os.system('ls xyz')
    ls: cannot access xyz: No such file or directory
    Out[2]: 512
    
    # with redirect
    In [3]: os.system('ls xyz 2> /dev/null')
    Out[3]: 512
    

    P.S. As pointed out by @Spencer Rathbun, the subprocess module should be preferred over os.system(). Among other things, it gives you direct control over the subprocess's stdout and stderr.