0

Whenever I run any .py script with sudo, even simple ones, I get the error "[Errno 13] Permission denied" on Linux. The reason I want to run a Python script with sudo in the first place is because the "keyboard" module in one of my files needs root permissions to function properly.

import keyboard

def record():
    events = keyboard.record(until='esc')
    return events

def process_recorded_letters(events):
    letter_events = ""

    for key in events:
        if key.event_type == 'down' and key.name != 'shift' and key.name != 'space':
            letter_events += key.name
    
    return letter_events

events = record()
print(process_recorded_letters(events))

I did the simple things like checking that I was actually the root user, checking if the files actually existed, and changing the file permissions with chown and chmod, but nothing worked, I kept on getting the Errno 13 error. I also tested running the script on a different Linux distro and I still got Errno 13, so it's definitely some problem on my end.

  • How are you running it? If directly, as in `./script.py` then it must be `+x` executable via `chmod`. – tadman Jul 14 '23 at 01:59
  • Yeah I did `chmod u+x my_file.py` and then `sudo python3 my_file.py` but it still doesn't work. – Sashank Bhagavatula Jul 14 '23 at 02:05
  • Does it execute without `sudo`? Does `sudo python3` do anything useful? – tadman Jul 14 '23 at 02:06
  • Without `sudo` it runs but then throws an error saying the keyboard module needs root permissions. `sudo python3` by itself works and enters the interactive python console. – Sashank Bhagavatula Jul 14 '23 at 02:09
  • 1
    Run `man sudo` and carefully read the text that talks about the execution environment. You probably have a `PYTHONPATH` env var (or other important env var) which is not being preserved by `sudo`. You also should update your question to show us the exact command you are running and the output. You should also clarify which "keyboard" module you are using. I'm guessing it is https://pypi.org/project/keyboard/ but the SO community shouldn't have to guess about such things. – Kurtis Rader Jul 14 '23 at 02:24
  • Also, the documentation for the keyboard module I linked to in my previous comment says: "To avoid depending on X, the Linux parts reads raw device files (/dev/input/input*) but this requires root." Which probably explains why you are trying to run your program via `sudo`. It would be simpler, and less risky from a security perspective, to add your user account to the "input" group so you don't need to use `sudo`. – Kurtis Rader Jul 14 '23 at 02:29
  • if you have `strace` installed, maybe you can try `sudo strace python x.py` to see which system call raises this error – yyyy Jul 14 '23 at 07:18

1 Answers1

1

I fixed it. I was using a OneDrive client and it was messing with Python's ability to access the file. Just copying and pasting the file somewhere else fixed the error. Thanks for the help everyone!