I have a little program that uses TKinter to open a csv.
All works fine.
When the user chooses a file, I want the cursor and the active window to return to the Python shell.
I am using this:
os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''')
When in IDLE, this works, when the program runs, but when I just double click the .py file and run it in the Python Shell, it says it can't find the path.
Anyone know the path I need?
Thanks,
Further research and this is my solution.
import win32gui as wg
from win32gui import GetWindowText, GetForegroundWindow
#This gets the details of the current window, the one running the program
aw = (GetForegroundWindow())
#Do some stuff..
#This tells the program to set the focus on the captured window
wg.SetForegroundWindow(aw)
I hope this helps anyone else looking for the same thing I was.
:-)
Try this, it refers to the running process via pid so it shouldn't matter exactly how you ran it:
import os
pid = os.getpid()
os.system("""/usr/bin/osascript -e 'tell application "System Events" to set frontmost of (first process whose unix id is %d) to true'""" % pid)
Related
I need to login to IBM i System using Python without entering the username and password manually.
I used py3270 library but it is not able to detect the Emulator wc3270. The emulator I use has .hod extension and opens with IBM i Launcher.
Can anyone help me with this? what could be the possible solution for this?
os.system() is a blocking statement. That is, it blocks, or stops further Python code from being executed until whatever os.system() is doing has completed. This problem needs us to spawn a separate thread, so that the Windows process executing the ACS software runs at the same time the rest of the Python code runs. subprocess is one Python library that can handle this.
Here is some code that opens an ACS 5250 terminal window and pushes the user and password onto that window. There's no error checking, and there are some setup details that my system assumes about ACS which your system may not.
# the various print() statements are for looking behind the scenes
import sys
import time
import subprocess
from pywinauto.application import Application
import pywinauto.keyboard as keyboard
userid = sys.argv[1]
password = sys.argv[2]
print("Starting ACS")
cmd = r"C:\Users\Public\IBM\ClientSolutions\Start_Programs\Windows_x86-64\acslaunch_win-64.exe"
system = r'/system="your system name or IP goes here"'
# Popen requires the command to be separate from each of the parameters, so an array
result = subprocess.Popen([cmd, r"/plugin=5250",system], shell=True)
print(result)
# wait at least long enough for Windows to get past the splash screen
print("ACS starting - pausing")
time.sleep(5)
print("connecting to Windows process")
ACS = Application().connect(path=cmd)
print(ACS)
# debugging
windows = ACS.windows()
print(windows)
dialog = ACS['Signon to IBM i']
print(dialog)
print("sending keystrokes")
keyboard.send_keys(userid)
keyboard.send_keys("{TAB}")
keyboard.send_keys(password)
keyboard.send_keys("{ENTER}")
print('Done.')
Currently, I am facing the same issue. I was able to run the IBMi (ACS), however, once it run, my python script stop functioning as if the app is preventing the python from being running. In generally speaking, the app seems to not detecting the script.But once I closed the app, my python script continue to work.. I put some indication e.g timesleep, however as i mentioned earlier, it only continue to that line of code once IBM is closed. There will be few lines to be added to move the selection to 5250 and inject the credential.
*I tried with pyautogui, still facing the same issue. so now i tried pywinauto import keyboard .
#Variables
dir = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]
x = dir.split("\\")
print(x[-1])
command = "cd \ && cd Users/Public/Desktop && " + '"' + x[-1] + '"'
print(command)
os.system(command)
------ FROM THIS LINE OF CODE ONWARDS, IT STOPPED RUNNING ONCE IBM IS LAUNCHED ---
print('TIME START')
time.sleep(5)
print('TIME END')
keyboard.send_keys(username)
keyboard.send_keys(password)
keyboard.send_keys("{ENTER}")
print('Done.')
Appreciate your help to look into this matter. Thanks
I'm working on a Python console app.
I want to check if the focus is on the console of my application.
I can assume my code will be executed on a Windows PC.
At the moment I'm using this unsafe version:
import win32gui
# Before the execution starts, I assume the focus will be on the console
CURRENT_CONSOLE = win32gui.GetForegroundWindow()
...
# Check if the console has the focus
if win32gui.GetForegroundWindow() == CURRENT_CONSOLE:
...
The obvious problem is that the user can change the focus before the execution arrives to the row that defines CURRENT_CONSOLE.
There is another problem:
If I'm debugging Visual Code with the integrated console, my method cannot tell whether the focus is on the console or somewhere else in the Visual Code window (for example on the code).
Try this:
import win32gui,win32process,os
focus_window_pid = win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow())[1]
current_process_pid = os.getppid()
print(focus_window_pid == current_process_pid )
win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow())[1] will get the parent process pid, so we need to use os.getppid() to get the parent pid of python process.
But if you are using other method to run your python script(eg: vscode), this method may not work.
Actually, I have written a code where I've to lunch the application such that I've to click the on-screen keyboard using this pyautogui.click(). But it is not working on on-screen keyboard. I'll be pleased to have your precious opinion. Thanks in advance.
import os
import pyautogui as pg
import time
x= 195
y=505
secret="secretpassword"
command = "application"
os.system(command)
pg.click(x, y)
pg.typewrite(secret)
pg.typewrite(["enter"])
If the application is already lunched this is working but i want to lunch it with os.system(command)
and after that enter my password and access to the application.
Am I doing something wrong ?
I changed
os.system(command)
with
subprocess.Popen(command)
Now it's working
subprocess.Popen() is strict super-set of os.system().
os.system() will block and wait for the application to exit.
This means that your click, in fact, will not execute until the opened appication closes.
To verify this, you can open a (python) shell and run following code:
import os
import pyautogui
def test():
os.system('<something simple opening a window>')
pyautogui.typewrite("I'm in the shell again!")
test()
To run your script as you want, use os.popen, or, even better, subprocess.Popen. These will run the command without blocking.
If you do this, keep in mind your application will have startup time, so you will want to wait some time after the call as noted in the comments under your question.
I want to just print some information and call an application e.g. notepad.
from subprocess import call
print("Opening Notepad++")
call([r"C:\Program Files (x86)\Notepad++\notepad++.exe"])
exit()
Problem now is that the terminal window doesn't automatically close. It stays open until I close the notepad window. How can I make the terminal window disappear automatically.
use Popen like so
import subprocess
subprocess.Popen(r'C:\Program Files (x86)\Notepad++\notepad++.exe', \
stdout=subprocess.PIPE, shell=False, creationflags = 0x08000000)
You need to call the notepad command with start COMMAND, like in Linux we use COMMAND & to fork the process into the background. in windows we use the start COMMAND
So you code refactored:
from subprocess import call
print("Opening Notepad++")
call([r"start C:\Program Files (x86)\Notepad++\notepad++.exe"])
exit()
Although note I don't have a windows machine to test on.
You could use pythonw.exe:
pythonw script.py
Or change its extension to pyw e.g. script.pyw and double click on it.
If you do that you should print "Opening Notepad++" to a popup window. See: Python Notification Popup that disappears
I am trying to write a downloader script (placed in unity luncher) using python that calls wget with all the right arguments. The script extracts url from clipboard and the file name from gtk primary clipboard, the one operated by text selection or copy and middle mouse click for paste. The code is rather simple.
import gtk
from os import system as sys
url = str(gtk.clipboard_get().wait_for_text())
name = str(gtk.clipboard_get(gtk.gdk.SELECTION_PRIMARY).wait_for_text())
if name.lower()=='none' :
sys("/usr/bin/canberra-gtk-play --id='dialog-warning'")
exit(1)
sys("/usr/bin/canberra-gtk-play --id='downloading'")
com='wget -c -t 0 "%s" -O "%s"' % (url,name)
sys("gnome-terminal -e '%s'" % com)
the script opens a terminal window and pints the wget output. The problem is that closing the gnome-terminal doesnt cause wget to exit, rather it runs in the background. Is it possible to stop this from happening
The problem is that, by design, wget ignores the SIGHUP which is sent when its parent process terminates.
One solution would be to use the python signal module to catch the SIGCHLD which should be sent to your script when you close the terminal window, and register a handler to explicitly send a SIGINT or SIGTERM to wget.