python中os.popen, os.system()区别
直接上个例子吧,注意结果,os.system的结果只是命令执行结果的返回值,执行成功为0:
1
2
3
4
5
6
7
8
9
10
|
>>> 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(),就可看到执行的输出:
1
2
3
4
5
6
|
>>> b = os.popen( 'ls' ) >>> b.read() 'Applications
Applications (Parallels)
Desktop
Documents
Downloads
GitHub_source
Library
Movies
Music
Pictures
Public
PycharmProjects
Python_Assignment
oradiag_shane
python-oldboy
python3.sublime-build
rpro.log
test.py
test.pyc
' >>> type (b) < class 'os._wrap_close' > >>> |
可以看出,输出的结果比较特殊,带换行符