python中os.popen, os.system()区别
直接上个例子吧,注意结果,os.system的结果只是命令执行结果的返回值,执行成功为0:
>>> a=os.system('ls') Applications Movies python-oldboy Applications (Parallels) Music python3.sublime-build Desktop Pictures rpro.log Documents Public test.py Downloads PycharmProjects test.pyc GitHub_source Python_Assignment Library oradiag_shane >>> a 0
可以看到,a为0
但用os.popen就可以读出执行的内容,popen返回的是file read的对象,对其进行读取使用read(),就可看到执行的输出:
>>> b=os.popen('ls') >>> b.read() 'Applications\nApplications (Parallels)\nDesktop\nDocuments\nDownloads\nGitHub_source\nLibrary\nMovies\nMusic\nPictures\nPublic\nPycharmProjects\nPython_Assignment\noradiag_shane\npython-oldboy\npython3.sublime-build\nrpro.log\ntest.py\ntest.pyc\n' >>> type(b) <class 'os._wrap_close'> >>>
可以看出,输出的结果比较特殊,带换行符\n