【问题标题】:Python: obtain the path to the home directory of the user in whose directory the script being run is locatedPython:获取正在运行的脚本所在目录的用户主目录路径
【发布时间】:2022-12-14 07:51:18
【问题描述】:

我有 a Python script 位于 /home/gabriel/dev/cpu_logger.py。在其中我正在登录/home/gabriel/cpu_log.log。我使用 pathlib.Path.home() 获取脚本中的 /home/gabriel 部分,如下所示。我将该部分用作我的log_file_path 的目录:

import pathlib

home_dir = str(pathlib.Path.home())
log_file_path = os.path.join(home_dir, 'cpu_log.log')

但是,我现在需要以 root 身份运行脚本允许它设置一些受限制的文件权限,所以我使用 crontab following these instructions here 将它配置为在启动时以 root 身份运行。现在,因为它以 root 身份运行,上面的 home_dir 变成了 /root,所以 log_file_path 变成了 /root/cpu_log.log那不是我想要的!我想让它登录到/home/gabriel/dev/cpu_logger.py

我怎样才能做到这一点?

但是,我不想显式设置该路径,因为我打算让其他人使用此脚本,因此不得对其进行硬编码。

我考虑将主用户的用户名作为第一个参数传递给程序,并使用os.path.expanduser("~" + username) 获取该用户的home_dir

import os
import sys

username = sys.argv[1]
home_dir = os.path.expanduser("~" + username)

...但如果不需要的话,我不想传递这样的额外参数。即使此脚本在 root 用户下运行,我如何才能将主目录设为 /home/gabriel

【问题讨论】:

    标签: python linux path


    【解决方案1】:

    我想到了!:

    script_path_list = os.path.normpath(__file__).split(os.sep)
    home_dir = os.path.join("/", script_path_list[1], script_path_list[2])
    

    解释

    __file__包含脚本的文件路径,所以我们可以用路径分隔符(/,或os.sep)拆分它,并读入我们需要的前几个组件。这是我想出的。下面的第一个参考非常有用。

    import os
    
    # Obtain the home dir of the user in whose home directory this script resides
    script_path_list = os.path.normpath(__file__).split(os.sep)
    home_dir = os.path.join("/", script_path_list[1], script_path_list[2])
    
    # print the results
    print("__file__         = {}".format(__file__))
    print("script_path_list = {}".format(script_path_list))
    print("home_dir         = {}".format(home_dir))
    

    为了帮助理解其工作原理,请查看上面的打印输出。您可以看到路径是如何拆分的,以及各种路径组件在 script_path_list 中的最终位置:

    __file__         = /home/gabriel/GS/dev/eRCaGuy_dotfiles/useful_scripts/cpu_logger.py
    script_path_list = ['', 'home', 'gabriel', 'GS', 'dev', 'eRCaGuy_dotfiles', 'useful_scripts', 'cpu_logger.py']
    home_dir         = /home/gabriel
    

    参考

    1. 很有用:How to split a dos path into its components in Python
    2. what does the __file__ variable mean/do?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-21
      • 2017-12-24
      • 1970-01-01
      • 2023-04-08
      • 2017-11-09
      相关资源
      最近更新 更多