Monday, June 10, 2013

Python's os.startfile() can run or edit a file

By Vasudev Ram

The startfile() function in the os module of Python's standard library can be used to run or edit a file programmatically. (The documentation also mentions 'print' as another operation, but I didn't try it yet. It will probably print to the default configured Windows printer on your system.)

The startfile() function is available on Python for Windows, and gives Python a subset of the funtionality of the Windows start command, i.e. the "start filename" command that can be used at the Windows (DOS) command prompt. The start command is useful because it lets you start (i.e. usually open) a file without giving the name of the program needed to open it as a prefix to the filename, i.e. instead of typing "programname filename", where programname is the program needed to open filename, like Microsoft Word to open a Word document, you can just type "start filename", and Windows invokes the program associated with that filename (by looking in the registry, I guess).

Here is a program showing how to use os.startfile():
import sys
import os

def test_startfile():
    filename = r'c:\temp\afile.bat'
    os.startfile(filename) # Default operation is 'run'
    #os.startfile(filename, 'edit') # Can specify 'edit' as the operation


And here is the file afile.bat used in the above example:
@echo off
echo This is afile.bat
echo Current directory is %CD%
dir c:\/s/p

I put the recursive dir command in the batch file because, without it, the program works, but the output flashes off the screen before you can see it. Even if you use a statement like "a = raw_input()" (to make the program pause until you enter something) after the call to startfile(), the output still flashes off, because the batch file is executed in a subprocess, and that process terminates before raw_input() is called.

When the edit operation ran, it opened afile.bat in the editor that I had configured to edit text files, i.e. Metapad, which is a good lightweight substitute for the default Windows Notepad.

So os.startfile() can be useful to run or edit external programs under the control of your Python application on Windows.

P.S. At the Windows command prompt, you can also use start command to open another command window, like this:
start cmd
or just
I do that often when working in Windows, to open another command window, to do some work in it, typically in another directory, without needing to change to that directory in the original window (though you can use pushd and popd nowadays in Windows, like you could in Unix shells, from long back). Or sometimes to edit a program from one command window and test it from the other window.

You can also use the Windows start command like this:
start /wait command
which makes the current process wait until the started command exits.

- Vasudev Ram - Dancing Bison Enterprises

No comments: