Gerhardus Meyer
Gerhardus Meyer

Reputation: 31

Python os with pyautoGUi module

I cannot get python to type "Hello world!" in the Notepad window when launching it via OS or subprocess. The "Hello world!" only gets typed after I close the notepad window, why would this be?

Code below:

import os
import pyautogui

os.system('"C:\\Windows\\System32\\notepad.exe"')
pyautogui.typewrite('Hello world!')

Upvotes: 3

Views: 756

Answers (1)

aschultz
aschultz

Reputation: 1678

While you can run notepad from the command prompt and then get the cursor back, os.system or even subprocess.run doesn't work that way on Python. Each waits until the process ID associated with your command is killed.

However, this code will work:

import subprocess
subprocess.Popen('"C:\\Windows\\System32\\notepad.exe"')
# we want to give notepad time to appear.
time.sleep(1)
pyautogui.typewrite("Hello world!")
exit()

There may be a more accurate command than time.sleep() to wait for Notepad to appear, something similar to WinWaitActive in AutoIt, and I'd be interested to hear it. But the above should work.

A possible workaround might be to create and then launch a new file in Notepad++ from the command line, or just to launch an already open instance of Notepad++ and have pyautogui send ctrl-n. I'm able to run multiple os.system calls in other scripts when opening text files in notepad++, as the process finishes once it find an open version of notepad++ to open the text file in.

echo > my_new_file.txt
os.system("my_new_file.txt")

os.system here cuts out once the file is launched, assuming Notepad++ was already open.

Upvotes: 2

Related Questions