如果您在文件上運行os.stat(path)
,然後取其st_mode
參數,那麼您如何從此處獲得像這樣的字符串:rw-r--r--
從Unix世界中已知?如何將狀態輸出轉換爲unix權限字符串
7
A
回答
11
因爲Python 3.3,你可以使用stat.filemode
:
In [7]: import os, stat
In [8]: print(stat.filemode(os.stat('/home/soon/foo').st_mode))
-rw-r--r--
In [9]: ls -l ~/foo
-rw-r--r-- 1 soon users 0 Jul 23 18:15 /home/soon/foo
2
下面的函數將實現這一點,給出一些常見的情況(即我沒有在Windows或SELinux下測試它)。
import stat
def permissions_to_unix_name(st_mode):
permstr = ''
usertypes = ['USR', 'GRP', 'OTH']
for usertype in usertypes:
perm_types = ['R', 'W', 'X']
for permtype in perm_types:
perm = getattr(stat, 'S_I%s%s' % (permtype, usertype))
if st_mode & perm:
permstr += permtype.lower()
else:
permstr += '-'
return permstr
這產生了一個基本的字符串,如問。然而,這也可以改進以顯示更多的數據,例如,無論是目錄(d
)還是符號鏈接(l
)。隨意改進它。
4
事情是這樣的:
import stat, os
def permissions_to_unix_name(st):
is_dir = 'd' if stat.S_ISDIR(st.st_mode) else '-'
dic = {'7':'rwx', '6' :'rw-', '5' : 'r-x', '4':'r--', '0': '---'}
perm = str(oct(st.st_mode)[-3:])
return is_dir + ''.join(dic.get(x,x) for x in perm)
...
>>> permissions_to_unix_name(os.stat('.'))
'drwxr-xr-x'
>>> ls -ld .
drwxr-xr-x 62 monty monty 4096 Jul 23 13:23 ./
>>> permissions_to_unix_name(os.stat('so.py'))
'-rw-rw-r--'
>>> ls -ld so.py
-rw-rw-r-- 1 monty monty 68 Jul 18 15:57 so.py
相關問題
- 1. 將ReadProcessMemory輸出轉換爲字符串
- 2. 將Redis輸出字符串轉換爲位字符串
- 3. Java:將Gzip字符串轉換爲輸出字符串
- 4. 如何將UnicodeEncoding輸出轉換爲純字符串?
- 5. 如何將Savant3模板的輸出轉換爲字符串?
- 6. 如何將輸出「__main__.Book對象」轉換爲字符串?
- 7. 如何將ostream_iterator的輸出轉換爲字符串?
- 8. 如何將字符串的命令輸出轉換爲整數?
- 9. 如何將控制檯輸出轉換爲字符串?
- 10. 如何將UNIX中的errno轉換爲相應的字符串?
- 11. 如何將HH:MM:SS字符串轉換爲UNIX紀元時間?
- 12. 如何將命令輸出轉換爲實時狀態更新?
- 13. 將Unix紀元作爲字符串轉換爲time.Time轉到
- 14. C#將字符串轉換爲字節並作爲字符串輸出
- 15. 如何將控制檯輸出的字符轉換爲字符串; C++
- 16. 如何將字符串的字符串轉換爲字符?
- 17. 將字符串轉換爲字符串
- 18. 將字符串轉換爲字符串
- 19. 將字符串轉換爲字符串
- 20. 如何將字符串轉換爲UInt32?
- 21. 如何將字符串轉換爲UTF8?
- 22. 如何將字符串轉換爲long
- 23. 如何將字符串轉換爲xml
- 24. 如何將OutputStream轉換爲字符串?
- 25. 如何將字符串轉換爲Guid
- 26. 如何將Ada.Real_TIme.Time轉換爲字符串?
- 27. 如何將BeautifulSoup.ResultSet轉換爲字符串
- 28. 如何將BigInteger轉換爲字符串?
- 29. 如何將字符串轉換爲DurationFieldType?
- 30. 如何將字符串轉換爲Bytearray
+1它可以在其他Python版本以及工作,只需從複製功能和相關數據[源代碼](http://hg.python.org/cpython/file/3.3/Lib/stat.py)。演示:http://ideone.com/P45ChT –