将变量从python传递到AppleScript

2024-03-29 05:06:45 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能告诉我如何使用python中的osascript将变量传递到Applescript中吗?我看过一些关于这样做的文档/示例,但我一点都不理解。在

下面是我的python代码:

# I want to pass this value into my apple script below
myPythonVariable = 10

cmd = """
    osascript -e '
    tell application "System Events"
        set activeApp to name of first application process whose frontmost is true
        if "MyApp" is in activeApp then
            set stepCount to myPythonVariableIPassIn

            repeat with i from 1 to stepCount
                DoStuff...
            end repeat
        end if
    end tell
    '
    """
os.system(cmd)

Tags: to文档cmd示例ifapplicationisend
1条回答
网友
1楼 · 发布于 2024-03-29 05:06:45

使用+运算符的字符串串联

myPythonVariable = 10
cmd = """
    osascript -e '
    tell application "System Events"
        set activeApp to name of first application process whose frontmost is true
        if "MyApp" is in activeApp then
            set stepCount to """ + str(myPythonVariable) + """

            repeat with i from 1 to stepCount
                  do something
            end repeat
        end if
    end tell
    '
    """

或者,使用{}的字符串格式:

^{pr2}$

{0}是第一个变量的占位符,{1}是第二个变量的占位符。。。。在

对于多个变量:

.format(myPythonVariable, var2, var3)


或者,使用%s运算符设置字符串格式

myPythonVariable = 10
cmd = """
    osascript -e '
    tell application "System Events"
        set activeApp to name of first application process whose frontmost is true
        if "MyApp" is in activeApp then
            set stepCount to %s

            repeat with i from 1 to stepCount
                  do something
            end repeat
        end if
    end tell
    '
    """ % myPythonVariable

对于多个变量:

% (myPythonVariable, var2, var3)

相关问题 更多 >