[Tutor] Invoking bash from within a python program

joe_schmoe geek_show at dsl.pipex.com
Sun Aug 14 12:33:09 CEST 2005


Danny Yoo wrote:
> 
> On Sat, 13 Aug 2005, Vinay Reddy wrote:
> 
> 
>>>Anyway, how do I call bash to run a program - e.g. slocate - from
>>>within a python program. I believe that I have to import the OS first
>>>(or do I?) and I was thinking something like:
>>>
>>>...
>>>sh slocate file_name > python_defined_list
>>
>>You can directly run slocate (or any other program) using the
>>os.popen* command. Refer to:
>>http://docs.python.org/lib/os-newstreams.html.
>>And you do need to import the os module.
> 
> 
> 
> Hi Joe,
> 
> Also, if you have a recent version of Python (Python 2.4), the
> 'subprocess' module might be worth a look:
> 
>     http://www.python.org/doc/lib/module-subprocess.html
> 
> 
> 
> 
>>>This is to populate a list which would then become the filename list
>>>for the remove file command to iterate through sequentially and
>>>delete, as in:
>>>
>>>for i in python_defined_list:
>>>       rm -fr i
> 
> 
> 
> 'shutil' and its rmtree() function may be helpful for you:
> 
>     http://www.python.org/doc/lib/module-shutil.html
> 
> Good luck!
> 
> 
Thanks Danny & Vinay

If I was to use the subprocess management module (as per Danny's 
suggestion), it looks like I should be able to invoke it using the 
shell=True argument. If my reading of 
http://www.python.org/doc/lib/node230.html is correct, this would enable 
the output of the command to be run through the shell (bash, in my case) 
without having to worry about piping the output back to the shell 
manually. This would then pass the list back to bash for it to iterate 
through the list to delete the filenames.

The basic idea I was toying around with is to create a delete/uninstall 
program that would take the output of slocate and iterate through that 
deleting all of the files associated with the program I wanted to 
uninstall without having to do so manually. Using tar balled source code 
does not seem to allow for an easy and straight forward way of 
uninstalling once the source directory has been deleted. I am also going 
to explore how to do this using bash and some basic shell programming 
and then work out which would be the better approach.

Thanks for your help folks.


More information about the Tutor mailing list