簡體   English   中英

如何在 Python 腳本中嵌入 AppleScript?

[英]How do I embed an AppleScript in a Python script?

我正在嘗試在 Python 腳本中嵌入 AppleScript。 我不想將 AppleScript 保存為文件,然后將其加載到我的 Python 腳本中。 有沒有辦法在 Python 中將 AppleScript 作為字符串輸入並讓 Python 執行 AppleScript? 謝謝一堆。

這是我的腳本: import subprocess 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()

使用子流程

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)

本文中的示例 3 建議:

#!/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()

然而,現在, subsystem.Popen通常比os.systemos.system (這篇文章來自三年前,當時沒有人看到os.system調用時尖叫;-)。

在python 3中它會略有不同:

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 現在需要一個類似字節的對象,要傳遞一個字符串,需要universal_newlines=True參數。

這是一個簡單的python3同步示例,如果您希望您的python代碼不等待Applescript完成。 在這個例子中,兩個say命令都是並行執行的。

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')

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)

等等。大多數建議,包括我引用的“applescript”,都缺少 osascript 的一個重要設置——將 -s 選項設置為“s”,否則您將難以解析輸出。

這是python中的一個通用函數。 只需使用/不使用 args 傳遞您的 Applescript 代碼,然后將值作為字符串返回。 感謝這個答案。

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'])

我不會嵌入 AppleScript,而是使用appscript 我從未使用過 Python 版本,但它在 Ruby 中非常好。 並確保,如果您在 Snow Leopard 上安裝它,您擁有最新版本的 XCode。 但是,到目前為止,我一直無法在 Snow Leopard 上安裝它。 但我只吃雪豹大約 1 天,所以你的里程可能會有所不同。

您可以使用os.system

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

或者,正如 Alex Martelli 所建議的,您可以使用一個變量:

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

subprocess.run() 現在優於subprocess.popen() 這是運行 AppleScript 代碼並返回結果的一種非常簡單的方法。

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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM