views:

17

answers:

1

I have a format holding paths to files and command line arguments to pass to those files when they are opened in Windows.

For example I might have a path to a javascript file and a list of command line arguments to pass it, in such a case I want to open the javascript file in the same way you might with os.startfile and pass it the command line arguments - since the arguments are saved as a string I would like to pass it as a string but I can also pass it as a list if need be.

I am not quite sure what I should be using for this since a .js is not an executable, and thus will raise errors in Popen while startfile only takes verbs as its second command.

This problem can be extended to an arbitrary number of file extensions that need to be opened, and passed command line arguments, but will be interpreted by a true executable when opening.

+2  A: 

If windows has registered the .js extension to open with wscript, you can do this, by leaving that decision up to the windows shell.

You can just use os.system() to do the same thing as you would do when you type it at the command prompt, for example:

import os
os.system('example.js arg1 arg2')

You can also use the start command:

os.system('start example.js arg1 arg2') 

If you need more power, for example to get results, you can use subprocess.Popen(), but make sure to use shell=True (so that the shell can call the right application):

from subprocess import Popen
p = Popen('example.js arg1 arg2', shell=True)
# you can also do pass the filename and arguments separately:
# p = Popen(['example.js', 'arg1', 'arg2'], shell=True)
stdoutdata, stderrdata = p.communicate()

(Although this would probably require cscript instead of wscript)

If Windows doesn't have any default application to open the file with (or if it's not the one you want), well, you're on your own of course...

Steven