0

I'm trying to make a python script pass characters from a text file as keystrokes into OSX. The text file is formatted as a column of characters:

Which is being read into a list (called lines). This bit seems to work, as when I type lines[3], for example, the third character is printed, as expected.

I'm now trying to use applescript to pass this character as a keystroke to OSX, using the following:

import os 
for f in xrange ( VALUE ):
osascript -e 'tell application "System Events" to keystroke linesf]'

It doesn't seem happy about the list[f] part (syntax error, carat is beneath the final apostrophe). I suspect it's because the variable f is not available to this command, for some reason, but I'm not certain. Could anybody give any advice? I know that the bit in the for loop needs to be indented, but this dialogue won't let me indent it, for some reason. It is correct in the script that I am testing.

Thank in advance.

Edit:

Those were typos, it should be lines, not list, the colon should be there, and it should be indented. After fixing all of this, I have the same result. I can't just iterate through the list, this is only an excerpt of the for loop, it needs to be structured this way for the rest to work.

How do I fix the line beginning osascript?

I got this by editing the accepted answer from this question, by the way: Is there a sendKey for Mac in Python?

Community
  • 1
  • 1
Alex
  • 1,583
  • 20
  • 41

1 Answers1

1

What it's unhappy about is that you've tried to use a command line instruction within your Python program - Python sees osascript -e 'tell application "System Events" to keystroke list[f]' and thinks that you want to subtract e from osascript, but then has no idea what to do with the string 'tell application "System Events" to keystroke list[f]'.

There are many things you're doing wrong here. First off, the code you've posted can't possibly be what you actually have, because you're missing the colon from your for loop (it should be complaining about that instead) and haven't indented the code that goes inside your for loop. Second, you've imported os, which I assume you want in order to use os.system for your command line instruction. Third, you should not call a list list, because the name list is already in use for the actual list class (this is a useful thing to have around, because, for example, it lets you do things like list('foobar') to create the list ['f', 'o', 'o', 'b', 'a', 'r']). Fourth, if you want to loop over each item in a list, actually do that. Fifth, if you write a string like "keystroke x[y]", then the variables x and y (assuming they exist) are irrelevant: you've asked for the string to contain the actual letters 'x' and 'y' (and some square brackets). You need to actually build a string that contains the appropriate character from the list.

Community
  • 1
  • 1
Karl Knechtel
  • 51,161
  • 7
  • 77
  • 117