I have a python app that run bash shell commands that require root priviledges. In terminal I type "sudo python3 main.py" then load python app file. Python app run mostly sudo commands so I always have to run it with sudo python3 main.py. In the main.py file in the beginning I have import settings.py file that save some important settings. settings.py file read and write INI File in home folder /home/username/.config/myapp/config.ini. So when I run the main.py app the settings.py create a folder myapp inside /home/username/.config/ and then create the config.ini filename.
The problem is tha because I run the main.py app with sudo the folder myapp and config.ini file created with root owner. How can I avoid that?
I would like to import whole file settings.py as normal user.
main.py
#!/usr/bin/python3
import os
import sys
import subprocess
import settings
....
....
settings.py
import configparser
# Create directory
dirName = '/home/username/.config/myapp'
# Create target directory & all intermediate directories if don't exists
try:
os.makedirs(dirName)
print("Directory ", dirName, " Created ")
except FileExistsError:
print("Directory ", dirName, " already exists")
filename = "/home/username/.config/myapp/config.ini"
# Writing Data
config = configparser.ConfigParser()
config.read(filename)
try:
config.add_section("ethernet")
except configparser.DuplicateSectionError:
pass
config.set("ethernet", "wired", "")
config.set("ethernet", "wired_mac_address", "")
try:
config.add_section("wifi")
except configparser.DuplicateSectionError:
pass
config.set("wifi", "wireless", "")
config.set("wifi", "wireless_mac_address", "")
with open(filename, "w") as config_file:
config.write(config_file)
# Reading Data
config.read(filename)
keys = [
"wired",
"wired_mac_address"
]
for key in keys:
try:
value = config.get("ethernet", key)
print(f"{key}:", value)
except configparser.NoOptionError:
print(f"No option '{key}' in section 'ethernet'")
# Reading Data
config.read(filename)
keys = [
"wireless",
"wireless_mac_address"
]
for key in keys:
try:
value = config.get("wifi", key)
print(f"{key}:", value)
except configparser.NoOptionError:
print(f"No option '{key}' in section 'wifi'")