How to run an autohotkey script in Python (2.7) - python

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.

Related

windows terminal won't stay open when the python script runs

I'm trying to learn subprocess module in python, while coding, I found out that if you try to open a terminal using the below code it will open for a brief second and just closes it self. How do I solve that.
import subprocess
subprocess.run('ipconfig')
I've tried using this below code as well but won't work.
def test():
subprocess.Popen('ipconfig', close_fds=False)

pyinstaller: popen doesn't run after producing exe

I compiled my python application using pyinstaller and the exe works fine, but when I run it on a different machine without python any part of the code which contains subprocess.Popen()doesn't run.
I read too many questions but I couldn't wrap my head around this.
My popen line:
try:
process = subprocess.Popen(['python', os.path.abspath('about.py')],stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE,
shell=True)
except Exception as e:
print(e)
Note that the executable runs on the host machine, but on another machines it runs but fails when launching the popen.
===UPDATE====
The console shows nothing and doesn't print an exception, so I guess this is a problem with python not being found. How can I fix this?
===UPDATE2====
Following the suggestion of viilpe I used "exec(open..." but it required me to import the about.py module first; importing the module runs it on top of the main module.
Putting exec(open...) inside the try\except runs the main module and the about module alongside each other; ruining the application's GUI.
I'm using "kivy" as my GUI library.
Looks like you want to execute about.py but there is no python.exe in pyinstaller bundle.
As advised here you can do it this way:
exec(open('about.py').read())
The whole point of PyInstaller is to make the destination computer be able to run your script without having a standalone python installation. You can't run a subprocess on a tool which isn't (necessarily) installed.
There are various ways to run Python as a subprocess of itself natively; start by exploring the multiprocessing library.
If the requirement to run Python twice is not a hard one, the absolutely simplest solution is to import about and run the code as part of your script. This probably requires some refactoring of the code in about.py.

Python automate open application

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()

How did I get informations on the module I'm writing?

I'm writing my first complete python project with Vim. As I was modifying a
file I accidentally hit several keys that I can't find back and I get this
prompt:
I didn't know it was possible to get this kind of help on a module I am
writing and I have no idea how I got it, so my question is:
What command or tools allows to generate this kind on module information?
Several notes
The command is not a Vim command because the ouput was in an external
shell (so I probably use an equivalent to :![command].
I don't have any Vim plugin related to python installed so it was probably not generated by a plugin.
The command wasn't issued in an interactive python prompt since I started my vim from my bash prompt.
I have not idea of how many keystrokes I used.
My Vim command history and my bash history doesn't have a trace of what
happened.
I'm using zsh and oh-my-zshell
I know that this question might sound silly but I have no idea of which tool can do that and I have no mean to find what sequence of keystrokes I used.
You can use pydoc command to get module help
pydoc requests
if you are using the interactive python shell, you can use the help function:
>>> import requests
>>> help(requests.get)
it work on class instance too

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.

Categories

Resources