0

Trying to use the following code (which works fine in applescript) to work in Python , fairly new to Python so I am not sure how I can get this string to work properly.

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

I am confident the problem is with

window's

I have tried:

window\s

but that doesn't work I think I just have too many quotation marks and I am not sure how to write the string correctly, probably a really easy one so hopefully someone can steer me in the right direction.

bengerman
  • 113
  • 2
  • 10

1 Answers1

0

You should pass the list of arguments you want to execute rather than creating a string with all the arguments put together. You also shouldn't use the shell=true flag.

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()
augurar
  • 12,081
  • 6
  • 50
  • 65
  • Works great, thanks for the help. What does shell=true do? I have been using this OSA script for a while for various uses. – bengerman Jan 04 '16 at 00:57
  • @bengerman When you enter a command in a terminal, there is a "shell program" that handles things like pipes, I/O redirection, `~` expansion, etc., then calls into the OS to run the command. Since you are not using any of these features, you do not need `shell = true`; moreover it can be a security risk so it is better not to use it if you don't have to. For more info see [the module docs](https://docs.python.org/2/library/subprocess.html#frequently-used-arguments) and [this SO question](http://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess). – augurar Jan 13 '16 at 04:24