473,748 Members | 2,659 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

getopt or optparse options/arguments wrapping?

I wonder is there any way to make the wrapper program can wrap options
&& arguments for the the subprocess/command the wrapper will
execute? by getopt or optparse module?

This is something like the shell script like this:
optwrap=""
while [ $# -gt 0 ]; do
case $1 in
-a) do-something; shift
;;
-b) do-something; shift
;;
*) optwrap="$optwr ap $1 $2"
# collect the option and argument
shift
;;
esac
shift
done

$command $optwrap
# execute the command with $optwrap as subprocess

I want that all the options and arguments which are feed to this
scripts command line will be used by executing the sub command.

I need this because I now have finished a fs_backup script written in
python, it will execute tar && find to complete full and
differentiating/incremental backup for the file system level files,
and their restoring. This script will do different things by the
command line arguments, and execute find/tar in different ways, but
for being more flexible, I want some options of tar/find can also been
specified from the command line directly, and the script just transmit
those to tar/find simply.

Is there anyone can give me some advices?

Thank you.

Mar 16 '07 #1
3 1948
Rocky Zhou wrote:
I wonder is there any way to make the wrapper program can wrap options
&& arguments for the the subprocess/command the wrapper will
execute? by getopt or optparse module?
[snip]
I need this because I now have finished a fs_backup script written in
python, it will execute tar && find to complete full and
differentiating/incremental backup for the file system level files,
and their restoring. This script will do different things by the
command line arguments, and execute find/tar in different ways, but
for being more flexible, I want some options of tar/find can also been
specified from the command line directly, and the script just transmit
those to tar/find simply.
I'm not clear on exactly what it is you want. Are you trying to do
something like::

fs_backup --foo --bar x y z --tar-foo --tar-bar tx ty tz

where ``--foo --bar x y z`` gets handled by your command and ``--tar-foo
--tar-bar tx ty tz`` gets passed on through to the tar command?

STeVe
Mar 16 '07 #2
Well, I think I must have more explanation on my script. The script's
usage is like this:
~# fs_backup
Lack of backup identity name
program usage: fs_backup [OPTIONS] $identity
OPTIONS:
-a|--append [t/x[L]:$path, append 1 dir or file to $identity
t/x: include/exclude list, as -T/-X of 'tar'
L:file, append a batch of dirs/files to $identity by LIST
-d|--delete $path, delete 1 dir or file from $identity
-t|--type $type, specify the backup type: full/diff/incr
-D|--delete-outdated [f/d], delete outdated files/empty-dirs when
restoring.
-o 'option=value'
-w|--wrap 'wrap of tar options'
-h|--help, print this help message
For example, I want to backup /var/www/html, with excluding /var/www/
html/syssite/home/cache, and name this backup as pages, I will do
this:
sh# fs_backup -a t:/var/www/html pages
sh# fs_backup -a x:/var/www/html/syssite/home/cache pages
# These t/x have the same meaning of tar's '-T/-X'
sh# fs_backup -t full pages
sh# fs_backup -t incr pages

These will update /var/fs_backup/.table, (/var/fs_backup is 'datadir',
you can configure it to anywhere you like by editing the configuration
file, /etc/new/fs_backup.confi g):
pages, full, 20070204-231749, pages/pages.full.2007 0204-231749
pages, incr, 20070205-101011, pages/pages.incr.2007 0205-101011
.......

May be I want add something to 'pages':
sh# fs_backup -a t:/usr/local/apache2/htdocs pages
sh# fs_backup -t full pages

Once I want recovery from the backup, I will do this:
sh# fs_rstore pages
This fs_rstore is just a symlink to fs_backup. All the files from the
last full backup will be restored.

The actually thing the script done is like this:
2007-03-18 20:32:20 fs_backup DEBUG find /mnt/file/data/ -cnewer /var/
fs_backup/work/.ts ! -type d -print >>/tmp/fs_backup.work. incr.
1174221140.0.li st
2007-03-18 20:32:20 fs_backup DEBUG find /mnt/file/work/ -cnewer /var/
fs_backup/work/.ts ! -type d -print >>/tmp/fs_backup.work. incr.
1174221140.0.li st
2007-03-18 20:32:20 fs_backup DEBUG tar -czp -P -f /var/fs_backup/work/
work.incr.20070 318-203220.tgz -T /tmp/fs_backup.work. incr.
1174221140.0.li st .identity .dirs .files

..dirs .files is just a snapshot of the current directories, which can
be used to delete-outdated files when restoring. Here I used absolute
path by using tar's -P parameter. When fs_rstore, it will do this:
command = "tar -xpz -P -f %s.tgz -T %s" % (archive, self.t_files)

maybe I want add some parameters of tar, for example, --strip-path=X,
so I hope the fs_rstore can do this:
sh# fs_rstore pages --strip-path=X
rather than:
sh# fs_rstore pages -w '--strip-path=X'

What should I do?

Thank you.

Mar 18 '07 #3
Rocky Zhou wrote:
.dirs .files is just a snapshot of the current directories, which can
be used to delete-outdated files when restoring. Here I used absolute
path by using tar's -P parameter. When fs_rstore, it will do this:
command = "tar -xpz -P -f %s.tgz -T %s" % (archive, self.t_files)

maybe I want add some parameters of tar, for example, --strip-path=X,
so I hope the fs_rstore can do this:
sh# fs_rstore pages --strip-path=X
rather than:
sh# fs_rstore pages -w '--strip-path=X'

What should I do?
One possibility using argparse (http://argparse.python-hosting.com/)
would be to require the '--' pseudo-argument before all tar options.
Then you could do something like::

fs_rstore pages -- --strip-path=X --same-owner

That '--' pseudo-argument makes everything else after it into a
positional argument (even if they start with '-' or '--'), so you can
then just collect those positional arguments and add them to your
"command". Here's what that code might look like::
>>parser = argparse.Argume ntParser(prog=' fs_backup')
parser.add_ar gument('-a', '--append', metavar='[t/x[L]:]PATH')
parser.add_ar gument('-d', '--delete', metavar='PATH')
parser.add_ar gument('-t', '--type',
... choices=['full', 'diff', 'incr'])
>>parser.add_ar gument('identit y')
parser.add_ar gument('tar_opt ions', nargs='*')
parser.parse_ args('-a foo pages -- --strip-path=X')
args = parser.parse_ar gs(
... '-a foo pages -- --strip-path=X --same-owner'.split())
>>args.append
'foo'
>>args.identi ty
'pages'
>>args.tar_opti ons
['--strip-path=X', '--same-owner']
>>"tar %s -f %s.tgz" % (' '.join(args.tar _options), args.identity)
'tar --strip-path=X --same-owner -f pages.tgz'

Note that all the tar options got collected in 'args.tar_optio ns'.

You could get rid of the need for '--' by adding each tar options to
your parser with an add_argument() call, but I suspect that's too
tedious. I've added a feature request to argparse to make this kind of
thing easier::
http://argparse.python-hosting.com/ticket/28
Not sure when I'll have a chance to look into this though.

STeVe

P.S. You should be able to get similar behavior out of optparse, though
you'll have to parse the 'args' list yourself.
Mar 18 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2788
by: David Bear | last post by:
I'm stumped. Trying to follow the docs and .. failure. here's the args >>> args '-Middwb@mainex1.asu.edu -AKHAAM@prlinux+898 -CA --D2003-08-20-09:28:13.417 -Ff -Hprlinux --JTCPIP_NPF_TEST_DARS_PORTRAIT -NTCPIP_NPF_TEST_DARS_PORTRAIT --Pholdqueue -Qholdqueue -aacct -b2895 -d/var/spool/lpd/holdqueue -edfA898prlinux -fTCPIP_NPF_TEST_DARS_PORTRAIT -hprlinux -j898 -kcfA898prlinux -l66 -nKHAAM -sstatus -t2003-08-20-09:28:13.000 -w80 -x0 -y0...
3
2318
by: Dominik Kaspar | last post by:
I tried to use getopt and copied the example from: http://www.python.org/doc/current/lib/module-getopt.html but nothing is working... getopt.GetoptError doesn't seem to exist and when i run the program commenting this out, none of "-v", "-h" and "-o" wants to be recognized... what's the matter?! Dominik
3
7028
by: Don Low | last post by:
Hi, I'm going over a script that demonstrates the getopt function. I include the script here: #! /usr/bin/python import sys, getopt, string
8
2309
by: Hans-Joachim Widmaier | last post by:
I was really pleased when the Optik module found its way into the standard Python battery compartment, as it matched all my option parsing requirements. But, as always, there's really nothing that does all you ever want, especially when it comes to option parsing - there's just too many schemes to handle them all comfortably. With this program I'm working on, I started to recognize that not only the functionality should be delegated to...
6
3694
by: Frans Englich | last post by:
Hello, In my use of getopt.getopt, I would like to make a certain parameter mandatory. I know how to specify such that a parameter must have a value if it's specified, but I also want to make the parameter itself mandatory(combined with a mandatory value, the result is that the user must specify a value). Here's code illustrating my point(see the TODO):
4
5675
by: pinkfloydhomer | last post by:
I want to be able to do something like: myscript.py * -o outputfile and then have the shell expand the * as usual, perhaps to hundreds of filenames. But as far as I can see, getopt can only get one argument with each option. In the above case, there isn't even an option string before the *, but even if there was, I don't know how to get getopt to give me all the expanded filenames in an option.
0
1137
by: Steven Bethard | last post by:
I feel like I must be reinventing the wheel here, so I figured I'd post to see what other people have been doing for this. In general, I love the optparse interface, but it doesn't do any checks on the arguments. I've coded something along the following lines a number of times: class OptionArgParser(optparse.OptionParser): def __init__(self, *args, **kwargs): self.min_args = kwargs.pop('min_args', None) self.max_args =...
4
431
by: rick | last post by:
Consider the following piece of code: parser = optparse.OptionParser(usage="usage: %prog <input filename> <output filename", add_help_option=False) parser.add_option("-d", type="string", action="store", dest="DELIM", default="|", help="single character delimiter in quotes (default: |)") (options, args) = parser.parse_args() Is there any way I can add help for the arguments (<input filenameand
20
5826
by: Casey | last post by:
Is there an easy way to use getopt and still allow negative numbers as args? I can easily write a workaround (pre-process the tail end of the arguments, stripping off any non-options including negative numbers into a separate sequence and ignore the (now empty) args list returned by getopt, but it would seem this is such a common requirement that there would be an option to treat a negative value as an argument. Note that this is only a...
0
8996
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8832
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9386
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9333
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6078
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4608
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2217
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.