1

I would like to open a text file and then search immediately for a certain string and highlight it.

I use:

command ="open "+'"'+ file +'"'
os.system(command)

But I want something like:

command ="open "+'"'+ file +'"' + "then"+ "ctrl-F(string)"

Obviously this doesn't work, but is there a way to do this? I just want the text in string to be highlighted as it is with a normal CTRL+F.

AstroCB
  • 12,337
  • 20
  • 57
  • 73
Sam Weisenthal
  • 2,791
  • 9
  • 28
  • 66
  • 1
    The `open` causes the associated application to start running and load the file, so the `ctrl-F` + string would have to be sent to that app in a way that looked like a keypresses. [_Is there a sendKey for Mac in Python?_](http://stackoverflow.com/questions/1770312/is-there-a-sendkey-for-mac-in-python) may help. – martineau Apr 12 '15 at 02:38
  • Whether this is possible depends on whether the app in which the file will be opened takes a command-line argument indicating that strings matching the given string should be highlighted. – Blacklight Shining Apr 12 '15 at 02:38

1 Answers1

4

You're on the right track with open; to use +F (I'm assuming you're on OS X from your tags), you can use AppleScript to tell the System Events application to perform a keystroke:

os.system("open " + filename)

# You may need to add a sleep() here if the application is not already open and therefore needs time to load
os.system("""osascript -e 'tell application "System Events" to keystroke "f" using {command down}'""")
os.system("""osascript -e 'tell application "System Events" to keystroke \"""" + search_term + "\"'")
AstroCB
  • 12,337
  • 20
  • 57
  • 73
  • 1
    I would use triple-quoted strings at the Python level so as to avoid having to escape those double quotes. – Blacklight Shining Apr 12 '15 at 03:02
  • @BlacklightShining Yes – I was considering that whilst trying to figure out which backslashes go where, but I wanted it to be concise and avoid the unnecessary variables created in the question. – AstroCB Apr 12 '15 at 03:05
  • What unnecessary variables? I'm just recommending using triple quotes instead of double quotes for those two string literals—for example, `"""osascript -e 'tell application "System Events" to keystroke "f" using {command down}'"""`. – Blacklight Shining Apr 12 '15 at 03:07
  • How would I do logical and within `search term`? For example, can it match "cat" and "dog" even if they don't appear side by side? – Sam Weisenthal Apr 13 '15 at 18:27
  • 1
    @user99889 No - this simply triggers the system "Find" option and so is limited by what you would be able to do with CMD+F within the application as per usual. – AstroCB Apr 13 '15 at 18:30