Groovy lanaguge - How to destroy/switch to an application - groovy

I'm using the groovy language in robotic application (RPA Express). I can not figure out how to do two things in the groovy language.
I start an application with these command:
def proc = new ProcessBuilder( args )
Process process = proc.start()
My questions are:
How do I close this application? (I want to close the application at the end of the script)?
How do I switch to this application window? (I want to be sure the application window is always focused)?

Both depend on the OS.
You need to invoke a kill task command to kill the process by its pid (e.g. kill on Linux). As Joachim mentions in the comments, Process has destroy() and destroyForcibly().
You need to use the window manager API to focus the window of the given pid you want.

Related

Profiling in Odoo

I am new to odoo and code profiling. I am using py-spy to profile my odoo code, as I need a flame graph as the output of profiling. Everything is working fine with py-spy, but the issue is, the py-spy needs to be stopped by pressing ctrl + C on the terminal where it is running or shutting the odoo server down. I can't stop or reset the odoo server neither I can do ** Ctrl + C** on the server.
I had tried to create to do this
To start py-spy
def start_pyflame(self):
pyflame_started = self.return_py_spy_pid('py-spy')
error = False
if not pyflame_started:
self.start_pyflame()
else:
error = 'PyFlame Graph process already created. Use Stop button if needed.'
_logger.error(error)
which is working fine, the problem is with this one
def stop_pyflame_and_download_graph(self):
pyflame_running = self.return_py_spy_pid('py-spy')
if pyflame_running:
subprocess.run(["sudo", "pkill", "py-spy"])
Now the issue is when I am killing the process with pkill or kill it kills the process but along with this, it also terminates the py-spy, because of which, the output file is not generated.
Is there any way to stop or soft kill py-spy so that the output file will be created.
Thanks in advance for help
After some research, I came to know that all these kill commands are just killing the process whereas in this case, we need to stop the process.
This thing I have achieved by
sudo kill -SIGINT <pid>
As it is clear from the name, this command is not killing/terminating the process, it is simply asking the process to stop working by passing an interrupt signal.
This worked for me.

How do you "launch" a Windows protocol from Python?

We have a python script that needs to trigger the open of the Microsoft Store. We believe that the easiest way to do that is to use the ms-windows-store:// protocol.
We're currently doing that like this
import subprocess
ret = subprocess.call(["start", "ms-windows-store://pdp/?ProductId=9WZDNCRFHVJL"], shell=True)
Is that the recommended way to do this? I'm not sure if using start is correct here, or if there's something better?
Use os.startfile("ms-windows-store://pdp/?ProductId=9WZDNCRFHVJL"). This calls WINAPI ShellExecuteW directly. If you use subprocess, you have the expense of starting a child process. Plus CMD's start command will first search PATH to find a file that it can execute. Presuming nothing is found (and nothing likely will be, given this name), it hands the request off to ShellExecuteExW to let the OS shell handle it.

Windows Environment Variables - Troubling accessing updated environment variables in program

I have wrote an initialization script that sets user environment variables which are keys that have been hashed and encrypted...Once the keys have been created the key encryption exe is no longer required. I want to launch the main application and remove the init file containing the hashing and key encryption functions.
I am not having any trouble with any of the above...Everything works as should when independent of each other. The problem is that in order for the main application to have access to the newly created environment variables I need the init script to completely exit...
Everything I have tried, Popen with flags, os.system() and others have still left me in a situation where the parent process ends and the main application launches, however, the environment variables have not updated...I close and relaunch main.py and...boom the program sees the updated variables and all is fine.
All I want is the init script to run, spawn a new process that is not linked at all with init.py and then exit so it can be removed. I thought this would be simple but after many hours of head scratching and trying numerous things, I am still no closer.
If I have to I will simply bundle it as two separate .exe files but I wanted it to be a one click install type thing.
I am running windows 10 and this can be platform specific.
Links looked at:
How to stop/terminate a python script from running?
Using a Python subprocess call to invoke a Python script
Starting a separate process
https://docs.python.org/2/library/subprocess.html
Python: Howto launch a full process not a child process and retrieve the PID
And more...
Current closest result
p = Popen(["python","UserInterface.py"], stdin=PIPE, stdout=PIPE, stderr=PIPE,
creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
Create an environment block, set the environment variable using SetEnvironmentVariable, and use CreateProcess to specify this environment block for the created process.
MSDN DOC:
To specify a different environment for a process, create a new
environment block and pass the pointer to it as a parameter to the
CreateProcess function.
...
To programmatically add or modify system environment variables, add
them to the
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session
Manager\Environment registry key, then broadcast a WM_SETTINGCHANGE
message with lParam set to the string "Environment". This allows
applications, such as the shell, to pick up your updates.

How to completely exit a running asyncio script in python3

I'm working on a server bot in python3 (using asyncio), and I would like to incorporate an update function for collaborators to instantly test their contributions. It is hosted on a VPS that I access via ssh. I run the process in tmux and it is often difficult for other contributors to relaunch the script once they have made a commit, etc. I'm very new to python, and I just use what I can find. So far I have used subprocess.Popen to run git pull, but I have no way for it to automatically restart the script.
Is there any way to terminate a running asyncio loop (ideally without errors) and restart it again?
You can not start a event loop stopped by event_loop.stop()
And in order to incorporate the changes you have to restart the script anyways (some methods might not exist on the objects you have, etc.)
I would recommend something like:
asyncio.ensure_future(git_tracker)
async def git_tracker():
# check for changes in version control, maybe wait for a sync point and then:
sys.exit(0)
This raises SystemExit, but despite that exits the program cleanly.
And around the python $file.py a while true; do git pull && python $file.py ; done
This is (as far as I know) the simplest approach to solve your problem.
For your use case, to stay on the safe side, you would probably need to kill the process and relaunch it.
See also: Restart process on file change in Linux
As a necromancer, I thought I give an up-to-date solution which we use in our UNIX system.
Using the os.execl function you can tell python to replace the current process with a new one:
These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as OSError exceptions.
In our case, we have a bash script which executes the killall python3.7, sending the SIGTERM signal to our python apps which in turn listen to it via the signal module and gracefully shutdown:
loop = asyncio.get_event_loop()
loop.call_soon_threadsafe(loop.stop)
sys.exit(0)
The script than starts the apps in background and finishes.
Note that killall python3.7 will send SIGTERM signal to every python3.7 process!
When we need to restart we jus rune the following command:
os.execl("./restart.sh", 'restart.sh')
The first parameter is the path to the file and the second is the name of the process.

How to catch and act when prompted for user input in shell script?

I have a working shell script which calls another shell script to perform some action on some processes running on the server. This inner shell script sometimes prompt to enter the userid and password. If this happens I want to come out this inner script and want to perform kill -9 for the process. Can anyone please suggest on how to achieve this?
One more point, whatever my shell scripts does, I am recording this in a log file,so I assume when script prompts to enter userid and password, this info also get recorded in the log.So is their should be a way to check this in the log file.
I am working on Linux OS. Please check and advise.
You can kill your child script
after some timeout:
( cmdpid=$BASHPID; (sleep 10; kill -9 $cmdpid) & exec my-child-script )
In this case you will kill my-child-script after given period of time (10 sec).
You can't (easily) detect if you script is waiting for input (on standard input), the only working method is to use strace/ptrace, but it's too complex
and I don't think it's really worth it. The timeout-based approach seems to be by far more natural.
You can find here
some additional examples of this approach in this question:
Bash script that kills a child process after a given timeout
Regarding log files:
You can extract data from your log files using grep/sed. To make the answer more concrete, we need some extra data.

Resources