我尝试运行此代码
import os
path_a = r'D:\Prroject'
if os.system("cd " + path_a) == 1:
print("Invalid Path!")
else:
print("Valid Path!")
并获得输出
The system cannot find the path specified.
Invalid Path!
如何删除“ The system cannot find the path specified.
”并使输出仅打印“ Invalid Path!
”。
答案 0 :(得分:4)
您应该为此真正使用os模块,这是一种潜在的方法:
try:
os.chdir('doesntexist')
print('Valid Path!')
except:
print('Invalid Path!')
输出:
Invalid Path!
答案 1 :(得分:0)
将标准错误输出重定向到/ dev / null。
os.system("cd " + path_a + " 2>/dev/null")
此语法适用于bash类型的shell;如果您使用其他外壳,请查阅该外壳的手册。
但是,您应该注意,从cd
运行os.system()
很有可能是无用的,因为更改后的目录仅在os.system()
调用的整个生命周期中都持续存在。短。下次您运行os.system()
命令时,您将回到原始目录。