Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi line command to os.system

There may be something obvious that I'm missing here but searching google/so has not provided anything useful.

I'm writing a python script utilizes tkinter's filedialog.askopenfilename to open a file picker. Without getting into to much detail, I have the following line, which serves to bring the file picker to the front of the screen (taken directly from this helpful answer):

os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''')

As you can see from the above code snippet, this line is too long for pep8 guidelines and I'd like to break it down.

However, despite my best efforts I can't seem to get it to split. This is due (I think) to the fact that the line contains both single and double quotes, and unfortunately os.system seems to insist on it being a single line.

I've tried

  1. Triple quotes
  2. String literal patching (\ at end, and + at beginning of each line)
  3. Triple quotes on a per line basis

If it's relevant: using OSX and running python 3.6.4.

What is the correct (and ideally, minimal) way to go about breaking this line down?

like image 939
Peter Dolan Avatar asked Apr 25 '18 23:04

Peter Dolan


1 Answers

Using the much improved subprocess module is usually a much better, more powerful, and safer way to call an external executable.

You can of course pass variables with \n in them as the arguments as well.

Note, the double (()) are because the first parameter is a tuple.

import subprocess
subprocess.call((
    '/usr/bin/osascript', 
    '-e',  
    'tell app "Finder" to set frontmost of process "Python" to true',
    ))

There are at times reasons to call through the shell, but not usually.

https://docs.python.org/3.6/library/subprocess.html

like image 118
gahooa Avatar answered Nov 02 '22 14:11

gahooa