Execute a program with python, then send API commands to that program - python

I'm trying to write a python script that can launch DaVinci Resolve in headless mode, then send it some commands via its API, then close it.
What I'm looking for would look something like
Open resolve.exe with argument --nogui
Do stuff with the API here
Terminate this instance of Resolve
I've managed to launch an instance of Resolve in headless. But it always ends up being a subprocess of something else. While it's running as a subprocess, I can't get the API to communicate with it.
Here's the code of tried
import subprocess
args = ["C:\Program Files\Blackmagic Design\DaVinci Resolve\Resolve.exe", '--nogui']
resolve_headles = subprocess.Popen(args)
from python_get_resolve import GetResolve
resolve = GetResolve()
This should return an object of Resolve, but it always fails.
I believe this is because its running as a subprocess of my IDE
I've also tried this
from subprocess import call
dir = "C:\Program Files\Blackmagic Design\DaVinci Resolve"
cmdline = "Resolve.exe --nogui"
rc = call("start cmd /K " + cmdline, cwd=dir, shell=True)
This just has the same problem of Resolve running as a subprocess of Windows Command Processor.

Related

Python script running installer.exe without user interaction

I am "translating" powershell scripts in to python, and I am having problems when it comes to run a installer.exe because it has to be automatic and with 0 interaction from the user. They just have to run the script and it installs both program and Microsoft Visual C++ versions. I mean, run, install and close on the background.
On powershell, it was so simple like doing this:
Start-Process -Wait -FilePath "$pwd\VC\vcredist2013_x64.exe" -ArgumentList "/passive /norestart" -PassThru | Out-Null
On python, i tried this and more:
import subprocess
def startProgram():
SW_HIDE = 0
info = subprocess.STARTUPINFO()
info.dwFlags = subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = SW_HIDE
VC13=subprocess.Popen(r'vcredist2013_x64.exe', startupinfo=info)
VC13.wait()
startProgram()
But they are not working, the wizard still pops up.
You can try using the subprocess.run method instead, with the stdout and stderr parameters redirected to subprocess.DEVNULL. The /passive and /norestart arguments can be passed using the args parameter.
Here's an updated code snippet:
import subprocess
def startProgram():
subprocess.run(["vcredist2013_x64.exe", "/passive", "/norestart"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
startProgram()

How to login to IBM 5250 emulator using Python/Java/.NET? [duplicate]

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

Simple use of Python’s Subprocess.call to open multiple Mac apps

I’d like to open a few apps using a very simple python script:
from subprocess import call
call("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome")
call("/Applications/MongoDB Compass.app/Contents/MacOS/MongoDB Compass")
The problem is that opening them this way seems to open a terminal window along with the app itself - for chrome, it outputs this in the terminal for example:
Last login: Sun Oct 23 00:20:38 on ttys000
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome ; exit;
nick#Nicks-MBP ~ % /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome ; exit;
objc[3817]: Class WebSwapCGLLayer is implemented in both /System/Library/Frameworks/WebKit.framework/Versions/A/Frameworks/WebCore.framework/Versions/A/Frameworks/libANGLE-shared.dylib (0x7ffb45565ec8) and /Applications/Google Chrome.app/Contents/Frameworks/Google Chrome Framework.framework/Versions/106.0.5249.119/Libraries/libGLESv2.dylib (0x116ba9668). One of the two will be used. Which one is undefined.
So it hijacks the terminal and does not proceed to this next line:
call("/Applications/MongoDB Compass.app/Contents/MacOS/MongoDB Compass")
If I try to call these:
call(("/Applications/Google Chrome.app"))
call(("/Applications/MongoDB Compass.app"))
I get this error, with other posts stating that it may be a dir and not an app:
OSError: [Errno 13] Permission denied
How can this be fixed? Note that I do not want to do this despite it working:
os.system("open /Applications/" + app + ".app")
Because I need to be able to wait for the apps to finish opening before running another command, hence the use of Subprocess.call. Thank you.
UPDATE:
I now have this:
print("start")
call(
[("/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome")],
shell=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT,
)
print("end")
But the print("end") line only executes when I exit out of chrome. How can I get it to wait for Chrome to load and then print 'end' after? Also it requires Shell=True for some reason, otherwise it complains with:
FileNotFoundError: [Errno 2] No such file or directory: '/Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome
Updated Answer
This also appears to work and doesn't involve the shell:
import subprocess as sp
print("start")
sp.run(["open", "-a", "Google Chrome"])
print("end")
Original Answer
This appears to do what you want, though I have no explanation as to why:
import subprocess as sp
print("start")
sp.Popen(
["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"],
stdin =sp.DEVNULL,
stdout=sp.DEVNULL,
stderr=sp.DEVNULL)
print("end")

How to get cmd command output from subprocess.getoutput without console window? [duplicate]

I have a program with a GUI that runs an external program through a Popen call:
p = subprocess.Popen("<commands>" , stdout=subprocess.PIPE , stderr=subprocess.PIPE , cwd=os.getcwd())
p.communicate()
But a console pops up, regardless of what I do (I've also tried passing it NUL for the file handle). Is there any way to do that without getting the binary I call to free its console?
From here:
import subprocess
def launchWithoutConsole(command, args):
"""Launches 'command' windowless and waits until finished"""
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
return subprocess.Popen([command] + args, startupinfo=startupinfo).wait()
if __name__ == "__main__":
# test with "pythonw.exe"
launchWithoutConsole("d:\\bin\\gzip.exe", ["-d", "myfile.gz"])
Note that sometimes suppressing the console makes subprocess calls fail with "Error 6: invalid handle". A quick fix is to redirect stdin, as explained here: Python running as Windows Service: OSError: [WinError 6] The handle is invalid
just do subprocess.Popen([command], shell=True)
According to Python 2.7 documentation and Python 3.7 documentation, you can influence how Popen creates the process by setting creationflags. In particular, the CREATE_NO_WINDOW flag would be useful to you.
variable = subprocess.Popen(
"CMD COMMAND",
stdout = subprocess.PIPE, creationflags = subprocess.CREATE_NO_WINDOW
)
This works nicely in the win32api. The other solutions were not working for me.
import win32api
chrome = "\"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe\""
args = "https://stackoverflow.com"
win32api.WinExec(chrome + " " + args)
You might be able to just do subprocess.Popen([command], shell=False).
That's what I use anyways. Saves you all the nonsense of setting flags and whatnot.
Once named as a .pyw or run with pythonw it shouldn't open a console.

open and close application sequentially in python

I am trying to open and close an application sequentially. But the problem is the application is being opened but to enter to the next line which is the closing line of that application I have to manually close the application.
import os
os.system("scad3 file.txt")
os.system("TASKKILL /PID scad3.exe /T")
scad3 is the application i wish to run,but to enter the next line i.e., taskkilling line, I have to manually close the window
please let me know is there any way to solve it??
thank you very much in advance
I guess os.system is a blocking call. Try using the Popen Objects in python:-
import subprocess
p = subprocess.Popen("notepad.exe")
p.terminate()
Refer :https://docs.python.org/2/library/subprocess.html#popen-objects
You can try using popen to execute command then wait given time and try to get result or kill the subrocess if it hasn't finished.
import subprocess
def get_array_from_cmd_str(cmd_str):
cmd_str_parts = cmd_str.split(" ")
return [cmd_part for cmd_part in cmd_str_parts]
def run_command_str(command):
p = subprocess.Popen(get_array_from_cmd_str(command),
stdout = subprocess.PIPE, stderr = subprocess.PIPE).communicate()[0]
resp = {'out': p[0],
'err': p[1]}
return resp
to run a command use the "run_command_str" function above in this way:
import time
cmd = "scad3 file.txt"
cmd_out = run_command_str(cmd)
expected_execution_time = 5
time.sleep(expected_execution_time)
if cmd_out['err'] != '':
pass # handle error here
Now if your program does not close automatically you can modify the approach to manually kill it using methods descriged in this thread.
(examples not tested on Windows)
EDIT: Code modified according to valuable comment. Example makes a blocking call and does not address the issue; use other ones.

Categories

Resources