0

I am trying to automate some tasks using Python. The task involves running some .exe code, and the .exe code, at the end needs user to press a key to finish. Here is my problem:

In my code I need to run the .exe two times, so my code looks like this:

p = subprocess.Popen('MyCode.exe')
PressKey(13)
p.wait()
...
p = subprocess.Popen('MyCode.exe')
PressKey(13)
p.wait()

And the PressKey() function is copied from HERE.

My problem is that it looks like the first PressKey(13) function call works and causes the .exe subproces to finish and python will move on to the next line, but then the second time the subprocess is executed the PressKey(13) does not have any effect and the .exe code stays at the stage that asks user to press a key. I even tried adding a PressKey(13) after the p.wait() as well and it didn't help.

Any help on this is really appreciated.

TJ1
  • 7,578
  • 19
  • 76
  • 119
  • 1
    It might have to do with which task is in the foreground. The key is probably being sent, but to the wrong window. – Doyousketch2 Jun 29 '21 at 21:03
  • Thanks. How can I make sure my task is in the foreground? – TJ1 Jun 29 '21 at 21:04
  • I used to know how, but haven't been on Windows for years. in Linux it would be `xdotool search --name MyCode windowactivate`. *Automate the boring stuff with Python* comes to mind. **SO** might have answers, but you'd have to scrounge around. – Doyousketch2 Jun 29 '21 at 21:09
  • I looked at that book, it suggest to use `pyautogui` module. Unfortunately I cannot install any module and need to use whatever is already provided in python standard library. Any other suggestion? Thanks again. – TJ1 Jun 30 '21 at 16:31
  • a subprocess call to an [AutoHotKey script](https://en.wikipedia.org/wiki/Autohotkey)? – Doyousketch2 Jun 30 '21 at 16:52
  • You probably could do it with `ctypes`, but you'd have to study those function calls. Think this shows how to [locate the window](https://stackoverflow.com/questions/37501191/how-to-get-windows-window-names-with-ctypes-in-python) Then you might [send a key combo](https://stackoverflow.com/questions/43724561/python-ctypes-keyboard-event) to raise it. If you can't find the keycode there, search GitHub for `Python keyboard ctypes` – Doyousketch2 Jun 30 '21 at 17:03
  • oh wait, `PressKey(13)` is Pause. I thought that was Enter. Ya might try `PressKey(0D)` instead. -- https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes. or Alt-Tab... figure out what that key-combo is. – Doyousketch2 Jun 30 '21 at 17:22
  • isn't '0D' in hex the same as 13 in decimal? the argument in PressKey() is decimal. – TJ1 Jun 30 '21 at 17:55
  • oh yea yea, was expecting to see `0x` and it threw me off. – Doyousketch2 Jun 30 '21 at 18:38

0 Answers0