changing current dir and executing a shell script

Peter Otten __peter__ at web.de
Sat May 28 03:41:55 EDT 2011


Albert Hopkins wrote:

> On Fri, 2011-05-27 at 14:25 -0700, suresh wrote:

>> I want to execute the following command line stuff from inside python.
>> $cd directory
>> $./executable
>> 
>> I tried the following but I get errors
>> import subprocess
>> subprocess.check_call('cd dir_name;./executable')
>> 
>> Due to filename path issues, I cannot try this version.
>> subprocess.check_call('./dir_name/executable')

> You don't want to do this because "cd" is a built-in shell command, and
> subprocess does not execute within a shell (by default).

The problem is not that cd is built-in, but that there is no shell at all. 
You can change that with shell=True:

>>> subprocess.check_call("cd /usr/share; pwd; cd /usr/lib; pwd", 
shell=True)
/usr/share
/usr/lib
 
But I agree with you that 

> The proper way to do this is to use the "cwd" keyword argument to
> subprocess calls, i.e.:
> 
>>>> subprocess.check_call(('/path/to/exec',), cwd="/path/to/dir")




More information about the Python-list mailing list