Running external programs

# This script executes an external program. 
# In this case, this is the equivalent to either:
#  * [window key]+[r] and entering "http://google.com" 
#  *  entering the url on an 'explorer' window

#Script Parameters
program = 'explorer'
url = 'http://google.com'

#A. We need the Process class to execute external programs
from System.Diagnostics import Process

#B. Create new process instance
p = Process()

#B.1 Configure your process
p.StartInfo.UseShellExecute = False
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.FileName = program
p.StartInfo.Arguments = url

#C. Start the process and wait 
p.Start()
p.WaitForExit() 

5 comments:

Pushpendra Gangwar said...

I have put one more line at the end of this code:

print "IE has exited."

And i could see that WaitForExit() returns even when IE is not exited. Although this may be because IE has it's own way to live alive after some programs start it.. not sure or WaitForExit() not working.

Jose Leviaguirre said...

Hello Pushpendra,

I believe that, in this particular case, IE launches as a thread or different process. Maybe I put a bad example here, but it was meant for illustration purposes but might be useful when dealing with non threaded processes such as 'calc' (calculator).

WaitForExit Instructs the Process component to wait indefinitely for the associated process to exit. You can find a description to all properties and methods here:

https://msdn.microsoft.com/en-us/library/system.diagnostics.process(v=vs.110).aspx

Daniel Dolz said...

Hi,

Thanks a lot for this interesting post. I have modified your code to open instead a cmd window and create an empty file "blabla.txt" using:

program = "cmd.exe"
url= "/c echo.>blabla.txt"

When I run it on Spotfire, cmd window briefly pops up but the action is not performed. Could you guess why this is not working? Thanks!

Jose Leviaguirre said...

Hello daniel,

instead of calling cmd, you can create a file.bat that contains:
echo %1 > %2

on the script:
program='file.bat'
url='. blabla.txt'

but your blabla.txt file will be created where the spotfire is setup, something like:
C:\Users\xxx\AppData\Local\TIBCO\Spotfire\7.6.0\Modules\Spotfire DXP Forms_25.11.10220.7834

so it's better to put the entire path:
url='c:\\temp\blabla.txt'

file.bat can also be as simple as:
%1

on the script:
program = 'c:\\temp\\hello.bat'
args = 'echo.>c:\\temp\\blabla.txt'

Daniel Dolz said...

Hello Jose,

Thanks a lot. It works now :)