R BATCH jobs from Python

Terry Hancock hancock at anansispaceworks.com
Sun Nov 21 01:04:21 CET 2004

On Saturday 20 November 2004 05:30 pm, Benjamin Scott wrote:
> Author: Moosebumps
> Subject (1): Batch commands on Windows
> Subject (2): os.system always opens new window on Windows XP/2000
> here is the operation that works, but isn't actually carried out in
> Python:
> Start->Run "cmd" ***command line appears***
> then i enter the following commands (i copied and pasted the whole
> session so that you can see exactly what i did):
> ******************************************************
> Microsoft Windows XP [Version 5.1.2600]
> (C) Copyright 1985-2001 Microsoft Corp.
> C:\Documents and Settings\BRdir>cd c:\Applications\R\rw1091\bin
> C:\Applications\R\rw1091\bin>Rcmd BATCH c:\test.txt
> C:\Applications\R\rw1091\bin>
> ******************************************************

It would have been better to show us the Python code that *didn't*
work. ;-)

But I suspect it looks like this:

os.system('cd c:\Applications\R\rw1091\bin')
os.system('Rcmd BATCH c:\test.txt')

and your complaint is that the first 'cd' doesn't affect
the second command's context (i.e. they are in separate

You are right that os.system() uses separate shells, and
this is what it's supposed to do.

There are several fixes for this particular problem. One
is to do the 'cd' in python:

os.system('Rcmd BATCH c:\test.txt')

Another is to just run the command directly:

os.system('c:\Applications\R\rw1091\bin\Rcmd BATCH c:\test.txt')

Either should work fine for your example.

And, of course, it should be mentioned that there exists
a set of R bindings for Python so you could drive R directly,
instead of kludging a script driven from a system call in

You can also do it with popen, but it's probably less
intuitive than the solutions above (in general, popen isn't
really worth it unless you want to pipe the stdin/stdout
through your program -- which you don't seem to need here?).


Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com

More information about the Python-list mailing list