有人可以告诉我如何在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)
答案 0 :(得分:2)
使用 + 运算符
进行字符串连接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)