outputting a command to the terminal?

Steven Bethard steven.bethard at gmail.com
Mon Aug 14 12:33:56 EDT 2006


John Salerno wrote:
> Here's my new project: I want to write a little script that I can type 
> at the terminal like this:
> 
> $ scriptname package1 [package2, ...]
> 
> where scriptname is my module name and any subsequent arguments are the 
> names of Linux packages to install. Running the script as above will 
> create this line:
> 
> sudo aptitude install package1 package2 ...
> 
> It will run that line at the terminal so the package(s) will be installed.
> 
> Now, the extra functionality I want to add (otherwise I would just 
> install them normally!) is to save the package names to a text file so I 
> can now the names of programs I've manually installed, if I ever want to 
> check the list or remove packages.
> 
> So creating the proper bash command (sudo aptitude install ...) is easy, 
> and writing the names to a file is easy. But I have two questions:
> 
> 1. First of all, does Linux keep track of the packages you manually 
> install? If so, then I won't have to do this at all.
> 
> 2. Assuming I write this, how do output the bash command to the 
> terminal? Is there a particular module that Python uses to interact with 
> the terminal window that I can use to send the install command to the 
> terminal?


I don't know the answer to the first bit here, but I think the following 
should get you most of what you want as far as the second bit is concerned:


---------------------------- scriptname.py ----------------------------
import argparse # http://argparse.python-hosting.com/
import subprocess
import sys

def outputfile(filename):
     return open(filename, 'w')

if __name__ == '__main__':
     # parse the command line arguments
     parser = argparse.ArgumentParser()
     parser.add_argument('packages', metavar='package', nargs='+',
                         help='one of the packages to install')
     parser.add_argument('--save', type=outputfile, default=sys.stdout,
                         help='a file to save the package names to')
     namespace = parser.parse_args()

     # call the command
     command = ['sudo', 'aptitude', 'install'] + namespace.packages
     subprocess.call(command)

     # write the package name file
     for package_name in namespace.packages:
         namespace.save.write('%s\n' % package_name)
-----------------------------------------------------------------------


$ scriptname.py -h
usage: scriptname.py [-h] [--save SAVE] package [package ...]

positional arguments:
   package      one of the packages to install

optional arguments:
   -h, --help   show this help message and exit
   --save SAVE  a file to save the package names to



STeVe



More information about the Python-list mailing list