Python automate open application - python

Please give me idea regarding how to tackle this problem. I am not able to find any resource regarding this. Your help will be immensely valuable. So we have one limited license software. And want to reiterate the python invoking the application. If the application gives the error that licence is not available it should close the application and wait for sometime say 1 min and again invoke the process, it should do so endlessly until a licence is available and the application is finally open.
I am able to open the application using
Import os
os.startfile('application executable')
After this I want the application to know if there is an error window popping , it should close the window and wait for sometime and again open the application

os.startfile returns as soon as the associated application is launch so use Popen instead.
As you are using windows use these steps.
To Open a Shortcut using Popen on Windows first install pywin32
Step one:
python -m pip install pywin32
Step two:
Navigate to your python Scrips folder something like
C:\Users\Name\AppData\Local\Programs\Python\Python38-32\Scripts then type the command.
pywin32_postinstall.py -install
Then the code to use Popen is.
import subprocess
import win32com.client, win32api
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut(r'path to shortcut')
long_path = shortcut.Targetpath
p = subprocess.Popen(long_path)
p.wait()

Related

How to run an autohotkey script in Python (2.7)

I'm trying to run an autohotkey (ahk) script in Python 2.7 but nothing seems to work. All online sources I've found are either outdated or overly complicated.
Has anyone found a way of doing this? I just want to run a couple of simple scripts that activates windows and opens applications. E.g:
IfWinExist, Command Prompt - python ...
WinActivate
Update:
I've tried downloading pyahk:
ahk.start() # Ititializes a new script thread
ahk.ready() # Waits until status is True
ahk.execute(mw._['cwd']+"winActivate_cmd.ahk") # Activate cmd window
error: can't load autohotkey.dll
as well as trying this:
import win32com.client # Import library / module
dll = win32com.client.Dispatch("AutoHotkey.Script") #Creating DLL object?
dll.ahktextdll() #no idea what this is doing...
dll.ahkExec("WinActivate, Command Prompt - python")
pwintypes.com_error invalid class string
It seems like you should be able to just launch autohotkey with the script as a parameter using subprocess:
subprocess.call(["path/to/ahk.exe", "script.ahk"])
You'd have to check the autohotkey docs but this seems like it ought to work.

launch external shell python instance in shell from python

I'd like to call a separate non-child python program from a python script and have it run externally in a new shell instance. The original python script doesn't need to be aware of the instance it launches, it shouldn't block when the launched process is running and shouldn't care if it dies. This is what I have tried which returns no error but seems to do nothing...
import subprocess
python_path = '/usr/bin/python'
args = [python_path, '&']
p = subprocess.Popen(args, shell=True)
What should I be doing differently
EDIT
The reason for doing this is I have an application with a built in version of python, I have written some python tools that should be run separately alongside this application but there is no assurance that the user will have python installed on their system outside the application with the builtin version I'm using. Because of this I can get the python binary path from the built in version programatically and I'd like to launch an external version of the built in python. This eliminates the need for the user to install python themselves. So in essence I need a simple way to call an external python script using my current running version of python programatically.
I don't need to catch any output into the original program, in fact once launched I'd like it to have nothing to do with the original program
EDIT 2
So it seems that my original question was very unclear so here are more details, I think I was trying to over simplify the question:
I'm running OSX but the code should also work on windows machines.
The main application that has a built in version of CPython is a compiled c++ application that ships with a python framework that it uses at runtime. You can launch the embedded version of this version of python by doing this in a Terminal window on OSX
/my_main_app/Contents/Frameworks/Python.framework/Versions/2.7/bin/python
From my main application I'd like to be able to run a command in the version of python embedded in the main app that launches an external copy of a python script using the above python version just like I would if I did the following command in a Terminal window. The new launched orphan process should have its own Terminal window so the user can interact with it.
/my_main_app/Contents/Frameworks/Python.framework/Versions/2.7/bin/python my_python_script
I would like the child python instance not to block the main application and I'd like it to have its own terminal window so the user can interact with it. The main application doesn't need to be aware of the child once its launched in any way. The only reason I would do this is to automate launching an external application using a Terminal for the user
If you're trying to launch a new terminal window to run a new Python in (which isn't what your question asks for, but from a comment it sounds like it's what you actually want):
You can't. At least not in a general-purpose, cross-platform way.
Python is just a command-line program that runs with whatever stdin/stdout/stderr it's given. If those happen to be from a terminal, then it's running in a terminal. It doesn't know anything about the terminal beyond that.
If you need to do this for some specific platform and some specific terminal program—e.g., Terminal.app on OS X, iTerm on OS X, the "DOS prompt" on Windows, gnome-terminal on any X11 system, etc.—that's generally doable, but the way to do it is by launching or scripting the terminal program and telling it to open a new window and run Python in that window. And, needless to say, they all have completely different ways of doing that.
And even then, it's not going to be possible in all cases. For example, if you ssh in to a remote machine and run Python on that machine, there is no way it can reach back to your machine and open a new terminal window.
On most platforms that have multiple possible terminals, you can write some heuristic code that figures out which terminal you're currently running under by just walking os.getppid() until you find something that looks like a terminal you know how to deal with (and if you get to init/launchd/etc. without finding one, then you weren't running in a terminal).
The problem is that you're running Python with the argument &. Python has no idea what to do with that. It's like typing this at the shell:
/usr/bin/python '&'
In fact, if you pay attention, you're almost certainly getting something like this through your stderr:
python: can't open file '&': [Errno 2] No such file or directory
… which is exactly what you'd get from doing the equivalent at the shell.
What you presumably wanted was the equivalent of this shell command:
/usr/bin/python &
But the & there isn't an argument at all, it's part of sh syntax. The subprocess module doesn't know anything about sh syntax, and you're telling it not to use a shell, so there's nobody to interpret that &.
You could tell subprocess to use a shell, so it can do this for you:
cmdline = '{} &'.format(python_path)
p = subprocess.Popen(cmdline, shell=True)
But really, there's no good reason to. Just opening a subprocess and not calling communicate or wait on it already effectively "puts it in the background", just like & does on the shell. So:
args = [python_path]
p = subprocess.Popen(args)
This will start a new Python interpreter that sits there running in the background, trying to use the same stdin/stdout/stderr as your parent. I'm not sure why you want that, but it's the same thing that using & in the shell would have done.
Actually I think there might be a solution to your problem, I found a useful solution at another question here.
This way subprocess.popen starts a new python shell instance and runs the second script from there. It worked perfectly for me on Windows 10.
You can try using screen command
with this command a new shell instance created and the current instance runs in the background.
# screen; python script1.py
After running above command, a new shell prompt will be seen where we can run another script and script1.py will be running in the background.
Hope it helps.

Running external EXE from python

I'm running several portable apps from my python app.
Consider the following code:
import win32com.shell.shell as w32shell
import os
import sys
import win32process as process
PORTABLE_APP_LOCATION = "C:\\Windows\\System32\\calc.exe"
#This function runs a portable application:
def runPortable():
try:
startObj = process.STARTUPINFO()
process.CreateProcess(PORTABLE_APP_LOCATION,None,None,None,8,8,None,None,startObj)
# OR
#w32shell.ShellExecuteEx(lpFile=PORTABLE_APP_LOCATION)
except:
print(sys.exc_info()[0])
runPortable()
1) Should I expect any differences in the execution of this code from pythonw or python ?
2) If I change PORTABLE_APP_LOCATION to the path to a portable version of CDBurnerXP and use the ShellExecuteEx option instead of CreateProcess, I see the process is started on Windows Task Manager but the actual window of the app isn't visible. This doesn't happen with other EXEs such as a portable version of GIMP that do show up after being ran. I assume this difference comes from a property of the executables. Anybody knows what's causing this?
3) Under what terms does Windows prompts the "Are you sure you want to run this EXE"? I believe CDBurnerXP is signed with a certificate but still sometimes Windows pops this question when trying to run this EXE from within python.
Thanks a lot.
About Your first question , you should pay attention that when executing python code using pythonw.exe runtime , your sys.stdout buffer is limited to 4096 Bytes and when overflowed will throw an IOError wich you will not see because the code is running windowless .
I am a newbie in this field. May be this can help you
use subprocess.call, more info here:
import subprocess
subprocess.call(["C:\\temp\\calc.exe"])
or
import os
os.system('"C:/Windows/System32/notepad.exe"')
i hope it helps you...

Permissions Error: Within a python script, I need to find a server file in unix system and open it to run commands for the user

In a Unix system, within a python script, I am trying to open a terminal window and start a server. It is my understanding that python has a subprocess module that is supposed to allow such a thing. So:
import subprocess
subprocess.Popen(['path to terminal'])
returns:
OSError: [Errno 13] Permission denied
How do I run this with the right permissions? Or, is there a better, secure way to do what I need?
I'm relatively new to programming, so please reorient the discussion if my question is misguided. Thank you!
Edit: you state that you would like to execute /Applications/Utilities/Terminal.app, so you are apparently running Mac OS X.
Mac OS X .app programs are directories. They can be started with the Mac OS shell command open.
To open the program /path/to/server in a fresh Max OS Terminal session:
import subprocess
termapp=['open','-a','/Applications/Utilities/Terminal.app']
sp=subprocess.Popen(termapp+['/path/to/server'])
There's also a shell-command version of the terminal, so you do not need open -a.
import subprocess
termapp=['/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal']
sp=subprocess.Popen(termapp+['/path/to/server'])
The two ways have subtle differences in how the windows are grouped by the window manager. Each time you do the above you get another terminal process and another icon in the tray. While with -a a new window is opened within the same Terminal main program.

How do I add a python script to the startup registry?

I'm trying to make my python script run upon startup but I get the error message windowserror access denied, but I should be able to make programs start upon boot because teamviewer ( a third-party program I downloaded ) runs every time I restart my computer so I know that I should be able to make my program run at startup (I might be doing something different though, so if you could shed some light on what teamviewer is doing differently to get its script to run at startup that would be helpful).
Here is my script
import _winreg, webbrowser
key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,'Software\Microsoft\Windows\CurrentVersion\Run')
_winreg.SetValueEx(key,'pytest',0,_winreg.REG_BINARY,'C:\Users\"USERNAME"\Desktop\test.py')
key.Close()
webbrowser.open('www.youtube.com')
Any input is appreciated.
import webbrowser
webbrowser.open('www.youtube.com')
Get rid of all of that _winreg stuff. Instead, you (assuming double-clicking on a py file opens the console) should simply place it in your startup folder (C:\Users\yourusername\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup on Windows 7, and C:\Documents and Settings\yourusername\Start Menu\Programs\Startup in XP). This works because Windows tries to open all files in the startup folder, and if Python opens PYs by default, Windows will open the Python console. Try restarting, that should work.
Baboon:
I am a little late posting, but you seem to have left off the sam at the end of your code here.
When you open a key you need to add the user rights, if you do not _winreg defaults to "READ":
Here is a snippet from the python site
http://docs.python.org/2/library/_winreg.html#access-rights
sam is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_READ. See Access Rights for other allowed values.
Here is the code corrected:
import _winreg, webbrowser
key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER,'Software\Microsoft\Windows\CurrentVersion\Run',_winreg.KEY_SET_VALUE)
_winreg.SetValueEx(key,'pytest',0,_winreg.REG_BINARY,'C:\Users\"USERNAME"\Desktop\test.py')
key.Close()
webbrowser.open('www.youtube.com')

Categories

Resources