A system independent way using python to get the root directory/drive on which python is installed

会有一股神秘感。 提交于 2019-12-18 12:45:51

问题


For Linux this would give me /, for Windows on the C drive that would give me C:\\. Note that python is not necessarily installed on the C drive on windows.


回答1:


You can get the path to the Python executable using sys.executable:

>>> import sys
>>> import os
>>> sys.executable
'/usr/bin/python'

Then, for Windows, the drive letter will be the first part of splitdrive:

>>> os.path.splitdrive(sys.executable)
('', '/usr/bin/python')



回答2:


Try this:

import os

def root_path():
    return os.path.abspath(os.sep)

On Linux this returns /

On Windows this returns C:\\ or whatever the current drive is




回答3:


Here's what you need:

import sys, os

def get_sys_exec_root_or_drive():
    path = sys.executable
    while os.path.split(path)[1]:
        path = os.path.split(path)[0]
    return path



回答4:


Using pathlib (Python 3.4+):

import sys
from pathlib import Path

path = Path(sys.executable)
root_or_drive = path.root or path.drive


来源:https://stackoverflow.com/questions/12041525/a-system-independent-way-using-python-to-get-the-root-directory-drive-on-which-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!