-2

How can you add login item in system preferences with python using osascript or any other method on macos, Is this process right? subprocess.call("osascript -e add login items to System Preferences {Path: "/home"; value: hidden} at end, shell=True").

Blackmoon
  • 22
  • 4
  • 1
    Your question is not clear. Do you need help on how to call a process in Python, how to use osascript, or what exactly? – joanis May 13 '22 at 20:30
  • Hello, I would like to know whether it is possible to use osascript with python, and whether my way of doing it is right or wrong, if wrong what could be the correct solution. – Blackmoon May 13 '22 at 20:42

1 Answers1

1

Yes, you can use osascript with Python, but you will need to use the proper command syntaxes for both. I'm not sure where you came up with that script, but AppleScript terms can be found in an application's scripting dictionary (if it has one), in this case the Login Items Suite from System Events.

Since AppleScript only uses double quotes, using subprocess.call with a list of strings for the arguments can avoid a lot of quote escaping, and would be something like :

import subprocess

def add_login_item(item_name, item_path):
   script = ('tell application "System Events" to make new login item at end of login items with properties {name:"%s", path:"%s", hidden:false}' % (item_name, item_path))
   subprocess.call(['osascript', '-e', script])

add_login_item('Item Name', '/full/path/to/whatever.app')
red_menace
  • 3,162
  • 2
  • 10
  • 18
  • Hello, thanks, also can we add path in a different variable and then add it to subprocess.call. – Blackmoon May 22 '22 at 17:47
  • @Blackmoon - String interpolation runs into issues with the characters used, so to keep with avoiding a lot of escaping, you can use a string template or just add the string pieces and variables together. – red_menace May 22 '22 at 19:26
  • Actually, percent interpolation can also be used, but `format` and `f` strings use curly braces, which AppleScript also uses, so some escaping would need to be done for those. I’ve edited my answer to include a function that uses interpolation. – red_menace May 22 '22 at 21:31
  • Can we not just cancatenate with + operator. – Blackmoon May 23 '22 at 06:24
  • @Blackmoon - Yes, I mentioned that in my earlier comment. – red_menace May 23 '22 at 13:26