How to not print cmd output?

by Izzuddin Jamaluddin   Last Updated August 19, 2019 02:26 AM - source

I try to run this code

import os
path_a = r'D:\Prroject'

if os.system("cd " + path_a) == 1:
    print("Invalid Path!")
else:
    print("Valid Path!")

and get ouput

The system cannot find the path specified.
Invalid Path!

how to remove the "The system cannot find the path specified." and make the output only print "Invalid Path!" .



Answers 2


Redirect the standard error output to /dev/null.

os.system("cd " + path_a + " 2>/dev/null")

This syntax works with bash-type shells; if you use a different shell, consult that shell's manual.

However, you should be aware that running cd from os.system() is very likely to be useless, as the changed directory only persists for the lifetime of the os.system() call, which is very short. The next time you run a os.system() command, you will be back in the original directory.

John Gordon
John Gordon
August 19, 2019 02:20 AM

you should really use the os module for this, here's a potential approach:

try:
    os.chdir('doesntexist')
    print('Valid Path!')
except:
    print('Invalid Path!')

output:

Invalid Path!
Derek Eden
Derek Eden
August 19, 2019 02:22 AM

Related Questions


Images dimensions error in python

Updated February 24, 2018 05:26 AM



How to test Python 3.4 asyncio code?

Updated July 28, 2017 22:26 PM