Jak osadzić AppleScript w skrypcie Pythona?

Próbuję osadzić AppleScript w skrypcie Pythona. Nie chcę zapisywać Applescriptu jako pliku, a następnie ładować go w skrypcie Pythona. Czy istnieje sposób, aby wprowadzić AppleScript jako ciąg znaków w Pythonie i kazać Pythonowi wykonać AppleScript? Wielkie dzięki.

Oto mój scenariusz: podproces importu import re import os

def get_window_title():
    cmd = """osascript<<END
    tell application "System Events"
        set frontApp to name of first application process whose frontmost is true
    end tell
    tell application frontApp
        if the (count of windows) is not 0 then
            set window_name to name of front window
        end if
    end tell
    return window_name
    END"""

    p = subprocess.Popen(cmd, shell=True)
    p.terminate()
    return p

def get_class_name(input_str):
    re_expression = re.compile(r"(\w+)\.java")
    full_match = re_expression.search(input_str)
    class_name = full_match.group(1)
    return class_name

print get_window_title()
Author: dbmikus, 2010-05-31

9 answers

Use subprocess :

from subprocess import Popen, PIPE

scpt = '''
    on run {x, y}
        return x + y
    end run'''
args = ['2', '2']

p = Popen(['osascript', '-'] + args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(scpt)
print (p.returncode, stdout, stderr)
 24
Author: has,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-31 06:26:07

Przykład 3 w Ten artykuł sugeruje:

#!/usr/bin/env python
#sleepy-mac.py
#makes my mac very sleepy

import os
cmd = """osascript -e 'tell app "Finder" to sleep'"""
def stupidtrick():
     os.system(cmd)
stupidtrick()

W dzisiejszych czasach jednak subsystem.Popen jest zwykle preferowany zamiast os.system (artykuł jest sprzed trzech lat, kiedy nikt nie krzyczał na widok os.system rozmowy;-).

 5
Author: Alex Martelli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-31 01:13:36

W Pythonie 3 byłoby nieco inaczej:

script = 'tell "some application" to do something'
p = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True)
stdout, stderr = p.communicate(script)

Popen oczekuje teraz, że obiekt podobny do bajtów, aby przekazać ciąg znaków, potrzebny jest parametr universal_newlines=True.

 5
Author: gbonetti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-16 22:43:31

Zamiast osadzać AppleScript, użyłbym appscript . Nigdy nie używałem wersji Pythona, ale w Ruby było bardzo miło. i upewnij się, że jeśli instalujesz go na Snow Leopard, masz najnowszą wersję XCode. jednak do tej pory nie byłem w stanie zainstalować go na Snow Leopardzie. Ale ja miałem Snow Leoparda tylko od ~1 dnia, więc przebieg może się różnić.

 1
Author: Antal Spector-Zabusky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-31 07:58:16

Możesz użyć os.system:

import os
os.system('''
    osascript -e 
     '[{YOUR SCRIPT}]'
     '[{GOES HERE}]'
    ''')

Lub, jak zasugerował Alex Martelli, możesz użyć zmiennej:

import os
script = '''
    [{YOUR SCRIPT}]
    [{GOES HERE}]
'''
os.system('osascript -e ' + script)
 1
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-30 01:10:54

Oto ogólna funkcja w Pythonie. Wystarczy przekazać kod applescript z / bez args i odzyskać wartość jako ciąg znaków. Dzięki tej odpowiedzi.

from subprocess import Popen, PIPE

def run_this_scpt(scpt, args=[]):
    p = Popen(['osascript', '-'] + args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate(scpt)
    return stdout

#Example of how to run it.
run_this_scpt("""tell application "System Events" to keystroke "m" using {command down}""")

#Example of how to run with args.
run_this_scpt('''
    on run {x, y}
        return x + y
    end run''', ['2', '2'])
 1
Author: firesofmay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-01 04:14:18

Oto prosty przykład synchroniczny python3, jeśli chcesz, aby Twój kod Pythona nie czekał na zakończenie Applescript. W tym przykładzie oba polecenia say są wykonywane równolegle.

from subprocess import Popen

def exec_applescript(script):
    p = Popen(['osascript', '-e', script])

exec_applescript('say "I am singing la la la la" using "Alex" speaking rate 140 pitch 60')
exec_applescript('say "Still singing, hahaha" using "Alex" speaking rate 140 pitch 66')
 1
Author: Mark Chackerian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-01 19:40:00

Zobacz https://pypi.org/project/applescript/

import applescript
resp = applescript.tell.app("System Events",'''
set frontApp to name of first application process whose frontmost is true
return "Done"
''')
assert resp.code == 0, resp.err
print(resp.out)

Itd. Większość sugestii, w tym" applescript", które zacytowałem, brakuje jednego ważnego ustawienia dla osascript -- ustawienie opcji-s NA "s", W przeciwnym razie będziesz miał trudności z analizowaniem wyjścia.

 1
Author: Дмитрий Чернявский,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-26 04:55:08

subprocess.run() is now preferred over subprocess.popen(). Oto dość prosty sposób na uruchomienie kodu AppleScript i uzyskanie wyników z powrotem.

import subprocess

def get_window_title():
    cmd = """
        tell application "System Events"
            set frontApp to name of first application process whose frontmost is true
        end tell
        tell application frontApp
            if the (count of windows) is not 0 then
                set window_name to name of front window
            end if
        end tell
        return window_name
    """
    result = subprocess.run(['osascript', '-e', cmd], capture_output=True)
    return result.stdout

print(get_window_title())
 1
Author: Matthias Fripp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-31 00:48:30