SB87 SB87 - 5 days ago 6
Python Question

Python script does not work when started via osascript

Ok, so when I run this command:

sudo python3.5 /path/to/my/script.py


It executes fine and returns:


select user:


  1. Guest

  2. My username

    Choose the account that needs cleaning up (enter corresponding number):




After which I enter "2", press enter and the script runs great.

However, when I run:

osascript -e 'do shell script "python3.5 /Path/to/my/script.py" with administrator privileges'


I get the expected pop-up screen in which to enter my sudo-password, but afterwards it throws out the error:


OSError: [Errno 9] Bad file descriptor (1)needs cleaning up (enter
corresponding number):")


Anyone has any idea on this? Any help would be greatly appreciated!

PS; some background as to why I need this method --> I am using a pre-script (also written in python) from which myscript.py needs to be executed. My prescript.py does not need administrator privileges. Sometimes however, it will be required to call myscript.py which does need administrative privileges. Since I do not want to hard-code my sudo-password into any of my scripts I want to get a pop-up box asking me for it. I figured, telling my pre-script.py to run subprocess.Popen([]) on the osascript command I mentioned above would do the trick. However, for that, I first need to get the osascript command to work properly.

Answer

Ah, so I figured this one out myself. As expected it had to do with privileges. Somehow "do shell script" is run via other privileges then just entering the command in terminal. And "sudo command" in terminal does not equal (fully) to "do shell script [script] with administrator privileges".

For me, what fixed it, was navigating to:

System Preferences --> Security and Privacy --> Privacy tab --> Accessibility

And then dragging Python.app and Terminal.app to that window (you might need to unlock it first by pressing on the little lock in the lower-left corner of that window).

Comments