Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!')
like image 749
Gerhardus Meyer Avatar asked Aug 02 '26 02:08

Gerhardus Meyer


1 Answers

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.

like image 157
aschultz Avatar answered Aug 04 '26 18:08

aschultz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!