【问题标题】:How to use global variables inside of an Applescript function for a Python code如何在 Python 代码的 Applescript 函数中使用全局变量
【发布时间】:2021-12-14 20:08:06
【问题描述】:

如何在tell应用程序中从我的python脚本调用一个全局变量?这是可能去向的示例。假设我想从全局 python 变量中更改 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())

【问题讨论】:

    标签: python applescript message imessage osascript


    【解决方案1】:

    这是一个更好的例子:

    电话号码在第 7 行定义,在第 74 行输入。它在第 91 行从 applescript 内部调用。我想对来自第 98 行的 applescript 内部的消息执行相同的操作,就像电话号码能够做到的那样,而不是来自第 113 行(msg)。我想从 applescript 外部定义 msg 并像电话号码一样调用它。

    import subprocess, sys
     from os import system, name
     from time import sleep
    
    
     msg = ""
     Phone_num = ""
     repeat = ""
    
    
     def Ascii():
         clear()
         print("+++++++++++++++++++++++++++++++++++++++.")
         print("++++++++++++++77       77I++++++++++++++")
         print("++++++++++77               77+++++++++++")
         print("========77                   77=========")
         print("=======7                       7========")
         print("======7                         7=======")
         print("=====7                           7======")
         print("=====                             ======")
         print("=====                             ======")
         print("=====                             ======")
         print(
             "=====7                           7======    _ __  __                                "
         )
         print(
             "~~~~~~7                         7~~~~~~~   (_)  \/  |                               "
         )
         print(
             "~~~~~~~7                       7~~~~~~~~    _| \  / | ___  ___ ___  __ _  __ _  ___ "
         )
         print(
             "~~~~~~~~77                   77~~~~~~~~~   | | |\/| |/ _ \/ __/ __|/ _` |/ _` |/ _ \ "
         )
         print(
             "~~~~~~~~~~77               77~~~~~~~~~~~   | | |  | |  __/\__ \__ \ (_| | (_| |  __/"
         )
         print(
             "~~~~~~~~~~~~   77     777I~~~~~~~~~~~~~~   |_|_|  |_|\___||___/___/\__,_|\__, |\___|"
         )
         print(
             "~~~~~~~~~~~ 7I~~~~~~~~~~~~~~~~~~~~~~~~~~                                  __/ |     "
         )
         print(
             "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.                                 |___/     "
         )
         print("\nWith Python!")
         sleep(3)
    
    
     def intro():
         clear()
         print("Welcome to iMessage for Python.\n")
         print(
             "This Adapts From The AppleScript and Uses Elements From Python to Send Automated Messages to Others.\n"
         )
         print('This Uses US Based Numbers "(+1)" Only.\n')
    
         print(
             "?[WARNING] By Agreeing to Use this Software, Any Liability Due to Misuse Will NOT be Placed On the Author. ?"
         )
         sleep(5)
    
    
     def clear():
         _ = system("clear")
    
    
     def questions():
         clear()
         global msg, Phone_num, repeat
         print('NO Dashes "-", Spaces "_", or parentheses"()"  or the script WILL Fail.')
         print("Input Ex:XXXXXXXXX\n")
         Phone_num = str(input("Enter Here:"))
         clear()
         print("What is Your Message?\n")
         msg = input("Enter Here:")
         clear()
         print("How Many Times do You Want to Send this Message?\n")
         repeat = input("Enter Here:")
         clear()
    
    
     def apple():
    
         applescript = (
             """
         tell application "Messages"
             
             set targetBuddy to "+1 """
             + Phone_num
             + """"
             set targetService to id of 1st service whose service type = iMessage
             set i to 1
             set p to "Sent" 
             repeat {0}
                 
                 set textMessage to "{1}"
                 
                 set theBuddy to buddy targetBuddy of service id targetService
                 send textMessage to theBuddy
                 delay 1
                 
                 log ("Repeated " & i &" Time(s).") 
                 
                 set i to i + 1
                 
                 
             end repeat
             
         end tell
         """.format(
                 repeat, msg
             )
         )
         args = [
             item
             for x in [("-e", l.strip()) for l in applescript.split("\n") if l.strip() != ""]
             for item in x
         ]
         proc = subprocess.Popen(["osascript"] + args, stdout=subprocess.PIPE)
         progname = proc.stdout.read().strip()
    
    

    【讨论】:

    • 您已经使用format 以编程方式构建脚本字符串,为什么不对您要插入的所有项目执行相同的操作?
    【解决方案2】:

    您正在使用两种不同的方式以编程方式构建脚本字符串。一种方法使用连接,另一种方法使用字符串函数。使用其中一个可能不会那么混乱。

    format 函数使用传递的参数来替换字符串中的占位符。使用索引格式,参数可以以任意顺序多次使用(或根本不使用),因此此方法在构建此类脚本时为您提供了更多的灵活性。例如:

    msg = "This is a test."
    Phone_num = "8761234"
    repeat = "5"
    
    applescript = (
    """
    tell application "Messages"
       
       set targetBuddy to "+1 {0}"
       set targetService to id of 1st service whose service type = iMessage
       set i to 1
       set p to "Sent" 
       repeat {1}
          
          set textMessage to "{2}"
          
          set theBuddy to buddy targetBuddy of service id targetService
          send textMessage to theBuddy
          delay 1
          
          log ("Repeated " & i &" Time(s).") 
          
          set i to i + 1
       end repeat
    end tell
    """.format(Phone_num, repeat, msg)) # replace placeholders with variable values
    
    print(applescript)
    

    【讨论】:

    • 非常感谢。你是对的。这两种不同的格式是我所采用的。我现在明白了。
    • 通过字符串修改组装可执行代码是bad accidentwaiting to happen。不要那样做。例如尝试msg = 'Bobby says "Hello!"' 以无损演示您的代码将如何中断。这里也没有必要,因为 osascript 可以将其他参数转发给 AppleScript 的 run 处理程序。查看我的答案并将其添加到书签以供将来参考。
    【解决方案3】:

    如果您想将参数传递给 AppleScript,以下是正确的方法:

    #!/usr/bin/env python3
    
    import subprocess
    
    scpt = """
    on run {arg1, arg2}
        return arg1 + arg2
    end run
    """
    
    arg1 = 37
    arg2 = 5
    
    proc = subprocess.Popen(['osascript', '-', str(arg1), str(arg2)], 
        stdin=subprocess.PIPE, stdout=subprocess.PIPE, encoding='utf8')
    
    out, err = proc.communicate(scpt)
    print(out) # 42
    

    由于您使用的是 Python,因此您还可以选择py-applescript,即supported,或appscript,即not。如果您需要将复杂的参数传递给 AppleScript,py-applescript 库会自动在常见的 AS 和 Python 类型之间进行转换。 Appscript 完全避免使用 AppleScript,但您只能靠自己。

    【讨论】:

    • 我将检查并尝试您建议的所有内容。已收藏。谢谢!
    • 我应该提到我也写了 appscript 和 py-applescript,但不再支持任何一个。两者都是成熟的、完成的代码,其他开发人员继续提供维护版本。但是,如果/当 Apple 开始删除长期弃用的 Carbon API 时,我预计 appscript 将停止工作;如果他们曾经弃用 AppleScript 本身以支持一个光明的新快捷方式未来,那么这一切都变得毫无意义。)如果你的需求是适度的——简单的字符串参数并且对速度没有太大的需求——那么通过 osascript 调用 AppleScript 就足够了,并避免外部依赖。
    猜你喜欢
    • 2022-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多