views:

2233

answers:

5

I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?

A: 

os.system("open file.xls")

Dev er dev
Does "open" work on non-Mac OS X systems?
mipadi
Probably works on NeXTstep too. But certainly not Windows or UNIX. Given that the question asks about Excel, I'd assume OS X or Windows.
ephemient
+2  A: 

or

os.system("start excel.exe <path/to/file>")

(presuming it's in the path, and you're on windows)

and also on Windows, just start <filename> works, too - if it's an associated extension already (as xls would be)

warren
+4  A: 

I like popen2 for the ability to monitor the process.

excelProcess = popen2.Popen4("start excel %s" % (excelFile))
status = excelProcess.wait()

http://www.python.org/doc/2.5.2/lib/module-popen2.html

EDIT: be aware that calling wait() will block until the process returns. Depending on your script, this may not be your desired behavior.

MikeHerrera
+7  A: 

While the Popen answers are reasonable for the general case, I would recommend win32api for this specific case, if you want to do something useful with it:

It goes something like this:

from win32com.client import Dispatch
xl = Dispatch('Excel.Application')
wb = xl.Workbooks.Open('C:\\Documents and Settings\\GradeBook.xls')

Taken from a mailing list post but there are plenty of examples around.

Ali A
+3  A: 

The subprocess module intends to replace several other, older modules and functions, such as:

  • os.system
  • os.spawn*
  • os.popen*
  • popen2.*
  • commands.*

.

import subprocess

process_one = subprocess.Popen(['gqview', '/home/toto/my_images'])

print process_one.pid
Oli