Python script running installer.exe without user interaction - python

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

Related

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

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.

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.

rundeck unable to execute powershell script with import-module

I am running several python scripts via rundeck (in-line) on windows 2012 target node. These scripts used to run locally but now in the process of moving to rundeck.
One of the python scripts opens subprocess to invoke a powershell script and read the output.
import subprocess
CMD = [r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe ', '-File', r'C:\Users\Osman\Code\mop.ps1']
cmd = CMD[:]
cmd.append('arg1')
cmd.append('arg2')
cmd.append('arg3')
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
r = p.communicate()
print(r)
The mop.ps1 is
Import-Module MSOnline
$domain = $args[0]
$login = $args[1]
$pass = $args[2]
$EPass = $pass | ConvertTo-SecureString -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PsCredential($login, $EPass)
Connect-MsolService -Credential $Cred
$TenantId = Get-MsolPartnerContract -Domain $domain | Select-Object -ExpandProperty TenantId
Get-MsolAccountSKU -TenantId $TenantId | select SkuPartNumber,ActiveUnits,ConsumedUnits | ConvertTo-Csv -NoTypeInformation
This part of the code always fails to execute and if I check stderr it says:
Connect-MsolService : Exception of type 'Microsoft.Online.Administration.Automation.MicrosoftOnlineException' was thrown.
At C:\Users\Osman\Code\mop.ps1:7 char:1
+ Connect-MsolService -Credential $Cred
I'm not sure why it fails. I tried
Import-Module MSOnline -Verbose
And I can see Cmdlets being loaded. I tried creating profile.ps1 file in C:\WINDOWS\system32\WindowsPowerShell\v1.0\ location.
Everything works fine if I execute the code locally. I tried running a regular test .ps1 file 'disk.ps1' instead of my code, and that works fine because it doesn't load any modules:
get-WmiObject win32_logicaldisk -Computername $env:computername
What's the workaround to get a script with module to run properly? stdout is always empty.
Node is registered as 64 bit so I tried changing the cmd to
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe
I tried to copy profile.ps1 there, copied the Module there but still doesn't work via rundeck.
From your description, since you are able to get a valid output when running the script directly from the server, it may be possible that you error could be related to the “Second Hop” that you use to login into MS-Online. Currently, the Rundeck Python-Winrm plugin supports Basic, ntlm or CredSSP Authentication, and CredSSP authentication allows you to perform the second hop successfully.

Start a python script from grails 3

I created a web interface in Grails 3 where you can start different pipelines written in python via a web environment. I have created a simple form with a start button. The idea is now that when you press the start button the python pipeline is started. I can't figure it out I have tried several things a example is:
def cmd = "python amplicon_pipeline.py -i 'inputdir' -o 'outputdir' -a 'amplicon'"
def proc = cmd.execute()
proc.waitFor()
But nothing happens.
How can I get an external python script to start working when you press the start button?
Mention the full path to python and the script file.
Ex:
def cmd = ["/usr/bin/python", "/home/rm93/Documents/project_rivm/RIVM_amplicon_pipeline/amp‌​licon_pipeline.py", "-i", "/home/rm93/Documents/Git/BIGC_test_upload/amplicon_pipeline‌​/18/upload/", "-o", "/home/rm93/Documents/Git/BIGC_test_upload/amplicon_pipeline‌​/18/output/", "-a", "16sv4"]
def proc = cmd.execute()
proc.waitFor()
println proc.text

How to run an AppleScript from within a Python script?

How to run an AppleScript from within a Python script?
The questions says it all..
(On a Mac obviously)
this nice article suggests the simple solution
cmd = """osascript -e 'tell app "Finder" to sleep'"""
def stupidtrick():
os.system(cmd)
though today you'd use the subprocess module instead of os.system, of course.
Be sure to also check page 2 of the article for many more info and options, including appscript.
A subprocess version which allows running an original apple script as-is, without having to escape quotes and other characters which can be tricky. It is a simplified version of the script found here which also does parametrization and proper escaping (Python 2.x).
import subprocess
script = '''tell application "System Events"
activate
display dialog "Hello Cocoa!" with title "Sample Cocoa Dialog" default button 2
end tell
'''
proc = subprocess.Popen(['osascript', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
stdout_output = proc.communicate(script)[0]
print stdout_output
NOTE: If you need to execute more than one script with the same Popen instance then you'll need to write explicitly with proc.stdin.write(script) and read with proc.stdout.read() because communicate() will close the input and output streams.
I got the Output folks... Here it's following:
import subprocess
import sys
for i in range(int(sys.argv[1])):
ip = str(sys.argv[2])
username = str(sys.argv[3])
pwd = str(sys.argv[4])
script = '''tell application "Terminal"
activate
do script with command "cd Desktop && python test_switch.py {ip} {username} {pwd}"
delay 15
end tell
'''
proc = subprocess.Popen(['osascript', '-'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
stdout_output = proc.communicate(script.format(ip=ip, username=username, pwd=pwd))[0]
I was pretty frustrated at the lack of detail in Apple's own documentation regarding how to do this AND to also pass in arguments. I had to send the desired arg (in this case a zoom id) as a string otherwise the argument didn't come through to the applescript app
Here's my code running from python:
f = script if os.path.exists(script) else _tempfile()
if not os.path.exists(script):
open(f,'w').write(script)
args = ["osascript", f, str(zoom_id)]
kwargs = {'stdout':open(os.devnull, 'wb'),'stderr':open(os.devnull, 'wb')}
#kwargs.update(params)
proc = subprocess.Popen(args,**kwargs)
and here is my applescript:
on run argv
set zoom_id to 0
zoom_id = item 1 in argv
tell application "zoom.us"
--do stuff
end tell
end run

Categories

Resources