繁体   English   中英

从python将变量传递到AppleScript

[英]Pass variable into AppleScript from 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)

+运算符进行字符串连接

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

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

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 {0}

            repeat with i from 1 to stepCount
                -- do something
            end repeat
        end if
    end tell
    '
    """.format(myPythonVariable)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM