【问题标题】:Python osascript using extra quotation marksPython osascript 使用额外的引号
【发布时间】:2016-01-03 11:37:02
【问题描述】:

尝试使用以下代码(在 applescript 中运行良好)在 Python 中工作,这对 Python 来说相当新,所以我不确定如何让这个字符串正常工作。

def getChromeSource():
    cmdGetSource = """
    osascript -e 'tell application "Google Chrome" to set source to execute front window's active tab javascript "document.documentElement.outerHTML"'
    """
    proc = subprocess.Popen([cmdGetSource], stdout=subprocess.PIPE, shell=True)
    (source, err) = proc.communicate()

我相信问题出在

window's

我试过了:

window\s

但这不起作用,我想我只是有太多引号,我不确定如何正确编写字符串,可能是一个非常简单的字符串,所以希望有人可以引导我朝着正确的方向前进。

【问题讨论】:

  • 为什么不把它作为一个列表传递?
  • 你能给我看一个例子吗?

标签: python osascript


【解决方案1】:

您应该传递要执行的参数列表,而不是创建一个将所有参数放在一起的字符串。你也不应该使用shell=true 标志。

cmd_args = ['osascript', '-e', 'tell application "Google Chrome" to set source to execute front window\'s active tab javascript "document.documentElement.outerHTML"']
proc = subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
source, err = proc.communicate()

【讨论】:

  • 效果很好,感谢您的帮助。 shell=true 有什么作用?我已经将这个 OSA 脚本用于各种用途。
  • @bengerman 当您在终端中输入命令时,会有一个“shell 程序”处理管道、I/O 重定向、~ 扩展等事情,然后调用操作系统运行命令。由于您没有使用任何这些功能,因此您不需要shell = true;此外,它可能会带来安全风险,因此如果不需要,最好不要使用它。有关详细信息,请参阅 the module docsthis SO question
猜你喜欢
  • 1970-01-01
  • 2016-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-18
相关资源
最近更新 更多