I don't consider this question (How do I get the path and name of the file that is currently executing?) nor this one to be a duplicate of mine, because the answer to them is simply __file__
. My question and the situation is more complicated and deserves a place to be independently googlable. I'm seeking the home dir of the path in which the script lies, it turns out (and this isn't even the only solution, perhaps, as that's a solution detail not a problem description), not just the path in which the script lies. Also, the context surrounding my question is very unique (running the script as root but wanting the home dir of another user's file system in which the script lies), and deserves special attention as others will encounter it too I'm sure.
I have a Python script located in /home/gabriel/dev/cpu_logger.py
. Inside of it I am logging to /home/gabriel/cpu_log.log
. I obtain the /home/gabriel
part inside the script using pathlib.Path.home()
as follows. I use that part as the directory of my log_file_path
:
import pathlib
home_dir = str(pathlib.Path.home())
log_file_path = os.path.join(home_dir, 'cpu_log.log')
However, I now need to run the script as root to allow it to set some restricted file permissions, so I configured it to run as root at boot using crontab following these instructions here. Now, since it is running as root, home_dir
above becomes /root
and so log_file_path
is /root/cpu_log.log
. That's not what I want! I want it to log to /home/gabriel/dev/cpu_logger.py
.
How can I do that?
I don't want to explicitly set that path, however, as I intend this script to be used by others, so it must not be hard-coded.
I thought about passing the username of the main user as the first argument to the program, and obtaining the home_dir
of that user with os.path.expanduser("~" + username)
:
import os
import sys
username = sys.argv[1]
home_dir = os.path.expanduser("~" + username)
...but I don't want to pass an extra argument like this if I don't have to. How can I get the home dir as /home/gabriel
even when this script is running under the root user?