I have a tkinter Python 3 program that needs sudo privileges, so it checks for that and if you don't have it, it'll ask for your password and then rerun the program with sudo.
My current code works when just running the code like, python3 myscript.py
, but if I compile the script with python3 -m py_compile
and run it it gives me the below error.
Traceback (most recent call last):
File "myscript.py", line 339, in <module>
prompt = reload.communicate(input='{}\r\n'.format(password))[1]
File "/usr/lib/python3.5/subprocess.py", line 1072, in communicate
stdout, stderr = self._communicate(input, endtime, timeout)
File "/usr/lib/python3.5/subprocess.py", line 1757, in _communicate
self.stderr.encoding)
File "/usr/lib/python3.5/subprocess.py", line 976, in _translate_newlines
data = data.decode(encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9d in position 259:
invalid start byte
Again, this only happens after compiling the script and seems to be related to translate newlines option in subprocess.Popen.
Here's the bits of the troublesome code:
def get_userpassword():
userpassword = simpledialog.askstring("Password", "Please enter your password:", show='*')
return userpassword
password = get_userpassword()
reload = subprocess.Popen(['sudo', '-k', '-S', './' + __file__],
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
prompt = reload.communicate(input='{}\r\n'.format(password))[1]
I'm sure I'm missing something as I've put all this together using other bits of code found across the StackExchange, but no one seems to be doing it quite like this (compiling it). Or should I just forget it and give the users a warning to rerun the script with sudo?
A little more background, I'm trying to freeze this code with PyInstaller and found that the compiling process is where this stops working. Also, I'm writing this for some Linux users, who though being Linux users, are not experts and tend to shy away from doing things in the terminal. So if I can give them an app that has all the dependencies built in it will make my life and theirs easier. :)