How to run commands in command line from a script

Peter Hansen peter at engcorp.com
Fri Jul 1 00:07:00 EDT 2005


Ivan Shevanski wrote:
> Alright well I'm quite a noob and when I run a simple command to change 
> the current directory, nothing happens.  I made a little test script to 
> show it:
> 
> 
> import os
> cwd = os.getcwd()
> print cwd
> os.system('cd = C:\Program Files')
> print cwd

There are at least three errors in the above.

1. The command is "cd <path>", not "cd = <path>".  (Wow!  Just tried 
it... okay, technically it appears to work, but it doesn't seem to be 
the documented approach, and I've _never_ seen it before, but I have to 
admit it works. :-)

Okay then, two errors:

1. You are using a backslash without properly escaping it (as \\) or 
using a "raw" string (prefix the string with r as in r"my\string". 
Well, okay, in _this_ particular case you get away with it, because the 
\P sequence is not a special one, but if you'd use \t or \b or something 
like that it would not have worked.

So, then, only one error:

1. Commands like "cd" are executed by the shell, not as separate 
executables (.exe files).  Unfortunately, the result of this is that 
their effects are lost when the shell returns to Python, so you can't do 
what you are trying to do in quite this manner.

Generally, the only way to use an application (i.e. a program like the 
Python interpreter, or your own .exe) to change the working folder is to 
have your script executed from within a batch file, write out a new 
batch file in your script, and then have the calling batch file execute 
that script if it exists.  Roughly like this:

--------file mycd.bat----------
@echo off
if exist c:\temp\_mycd.bat del c:\temp\_mycd.bat
c:\python24\python.exe myscript.py
rem Note: file _mycd.bat written by myscript.py
if exist c:\temp\_mycd.bat call c:\temp\_mycd.bat

--------somewhere inside myscript.py--------
newDir = r'c:\Program Files'
f = open(r'c:\temp\_mycd.bat', 'w')
f.write('''rem This file generated by myscript.py
cd = %s''' % newDir)
f.close()

--------file _mycd.bat-----------
rem This file generated by myscript.py
cd = c:\Program Files


Hope that helps... :-)

-Peter



More information about the Python-list mailing list