Parviz Karimli
Parviz Karimli

Reputation: 1287

Passing administration privilege on Windows with Python

I have created a simple Tkinter app that creates a text file (if there is no one yet) and saves some log information in that file when the save button is clicked. But I have made a setup file (by cx_freeze) of my program (this is actually a small part of my main project), and when I install it in the default installation directory on a Windows PC (C:\Program Files), a user then is not able to create the log file due to the lack of administrator privilege (actually, it is not possible to create a file in Program Files in a "normal Windows way" either; you need to copy + paste the file). The easiest solution is of course including the log file on creating the program setup or running the program as administrator. But I do not want to include any log file or run the program as admin. So I am curious if there is any way to achieve it. I believe the subprocess module of Python can do something, but after reading some official and unofficial docs and also some SO threads about it, I am still not able to figure out how it can really solve my problem. By the way, here's my program snippet:

import tkinter as tk
import subprocess
import time

class App:
    def __init__(self, master):
        self.master = master

        self.saveBtn = tk.Button(self.master, text="Save", command=self.saveFn)
        self.saveBtn.pack()

    def saveFn(self):
        try:
            oldFile = open('log.txt', 'r')
            oldFileContent = oldFile.read()
            oldFile.close()

            newFile = open('log.txt', 'w')
            newFile.write(oldFileContent + '\n' + str(time.asctime()) + ';')
            newFile.close()
        except:
            file = open('log.txt', 'w')
            file.write(str(time.asctime()) + ';')
            file.close()

root = tk.Tk()
myApp = App(root)
root.mainloop()

Upvotes: 1

Views: 345

Answers (1)

KromviellBlack
KromviellBlack

Reputation: 918

You must not try to save your data to Program Files directory. This is the case for all big Operating Systems: for example you must not try to save your data to bin folder in Linux.

Your data should be placed inside the current user's directory (C:\Users\YourUserName).

To get path to current user's directory in Python (in cross-platform way) you may use code like this:

import os.path

path_to_users_directory = os.path.expanduser("~")

This code will place path to your current user's directory into path_to_users_directory variable

It will be 'C:\\Users\\YourUserName' uder Windows and '/home/YourUserName' under Linux.

Upvotes: 1

Related Questions