Convert all command line handling to argparse

Allows us to drop some hacks, and we may need it for a new upcoming
tool.
This commit is contained in:
Cole Robinson 2014-01-18 17:01:43 -05:00
parent 7f66926721
commit c426a30511
7 changed files with 287 additions and 331 deletions

View File

@ -145,6 +145,7 @@ class Command(object):
self.support_check = None
app, opts = self.cmdstr.split(" ", 1)
self.app = app
self.argv = [os.path.abspath(app)] + shlex.split(opts)
def _launch_command(self):
@ -944,6 +945,7 @@ _cmdlist += vconv.cmds
for _cmd in _cmdlist:
newidx += 1
setattr(CLITests, "testCLI%d" % newidx, maketest(_cmd))
setattr(CLITests, "testCLI%s%d" % (_cmd.app.replace("-", ""), newidx),
maketest(_cmd))
atexit.register(cleanup)

View File

@ -20,8 +20,8 @@
# MA 02110-1301 USA.
import argparse
import logging
import optparse
import sys
import urlgrabber.progress as progress
@ -129,73 +129,66 @@ def get_force_target(target, design):
def parse_args():
parser = cli.setupParser(
"%prog --original [NAME] ...",
"%(prog)s --original [NAME] ...",
_("Duplicate a virtual machine, changing all unique configuration "
"like MAC address, name, etc. The VM contents are not altered."))
cli.add_connect_option(parser)
geng = optparse.OptionGroup(parser, _("General Options"))
geng.add_option("-o", "--original", dest="original_guest",
geng = parser.add_argument_group(_("General Options"))
geng.add_argument("-o", "--original", dest="original_guest",
help=_("Name of the original guest; "
"The status must be shut off or paused."))
geng.add_option("--original-xml", dest="original_xml",
geng.add_argument("--original-xml", dest="original_xml",
help=_("XML file to use as the original guest."))
geng.add_option("--auto-clone", dest="auto_clone", action="store_true",
geng.add_argument("--auto-clone", dest="auto_clone", action="store_true",
help=_("Auto generate clone name and storage paths from"
" the original guest configuration."))
geng.add_option("-n", "--name", dest="new_name",
geng.add_argument("-n", "--name", dest="new_name",
help=_("Name for the new guest"))
geng.add_option("-u", "--uuid", dest="new_uuid",
geng.add_argument("-u", "--uuid", dest="new_uuid",
help=_("New UUID for the clone guest; Default is a "
"randomly generated UUID"))
parser.add_option_group(geng)
stog = optparse.OptionGroup(parser, _("Storage Configuration"))
stog.add_option("-f", "--file", dest="new_diskfile", action="append",
stog = parser.add_argument_group(_("Storage Configuration"))
stog.add_argument("-f", "--file", dest="new_diskfile", action="append",
help=_("New file to use as the disk image for the "
"new guest"))
stog.add_option("--force-copy", dest="target", action="append",
stog.add_argument("--force-copy", dest="target", action="append",
help=_("Force to copy devices (eg, if 'hdc' is a "
"readonly cdrom device, --force-copy=hdc)"))
stog.add_option("--nonsparse", action="store_false", dest="sparse",
stog.add_argument("--nonsparse", action="store_false", dest="sparse",
default=True,
help=_("Do not use a sparse file for the clone's "
"disk image"))
stog.add_option("--preserve-data", action="store_false",
stog.add_argument("--preserve-data", action="store_false",
dest="preserve", default=True,
help=_("Do not clone storage, new disk images specified "
"via --file are preserved unchanged"))
parser.add_option_group(stog)
netg = optparse.OptionGroup(parser, _("Networking Configuration"))
netg.add_option("-m", "--mac", dest="new_mac", action="append",
netg = parser.add_argument_group(_("Networking Configuration"))
netg.add_argument("-m", "--mac", dest="new_mac", action="append",
help=_("New fixed MAC address for the clone guest. "
"Default is a randomly generated MAC"))
parser.add_option_group(netg)
misc = optparse.OptionGroup(parser, _("Miscellaneous Options"))
misc = parser.add_argument_group(_("Miscellaneous Options"))
# Just used for clone tests
misc.add_option("--clone-running", action="store_true",
misc.add_argument("--clone-running", action="store_true",
dest="clone_running", default=False,
help=optparse.SUPPRESS_HELP)
help=argparse.SUPPRESS)
cli.add_misc_options(misc, prompt=True, replace=True, printxml=True)
parser.add_option_group(misc)
(options, parseargs) = parser.parse_args()
return options, parseargs
return parser.parse_args()
def main(conn=None):
cli.earlyLogging()
options, parseargs = parse_args()
options = parse_args()
options.quiet = options.quiet or options.xmlonly
cli.setupLogging("virt-clone", options.debug, options.quiet)
if parseargs:
fail(_("Unknown argument '%s'") % parseargs[0])
cli.set_prompt(options.prompt)
cli.set_force(options.force)

View File

@ -21,13 +21,13 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA.
import sys
import os
import logging
import argparse
import errno
from optparse import OptionGroup
import logging
import os
import sys
import virtinst.cli as cli
from virtinst import cli
from virtinst.cli import fail, print_stdout, print_stderr
import virtconv.formats as formats
import virtconv.vmcfg as vmcfg
@ -43,97 +43,114 @@ def get_default_arch():
def parse_args():
"""Parse and verify command line."""
opts = cli.setupParser(
"%prog [options] inputdir|input.vmx [outputdir|output.xml]",
parser = cli.setupParser(
"%(prog)s inputdir|input.vmx [outputdir|output.xml] [options]",
_("Convert from virtual machine descriptor format to another. The "
"VM contents are not altered."))
cong = OptionGroup(opts, "Conversion Options")
cong.add_option("-i", "--input-format", dest="input_format",
parser.add_argument("input", metavar="inputconfig", nargs=1,
help=_("Conversion input: flat file or directory."))
def add_output_arg(p):
p.add_argument("output", metavar="outputconfig", nargs='?',
help=_("Conversion destination"))
add_output_arg(parser)
cong = parser.add_argument_group("Conversion Options")
cong.add_argument("-i", "--input-format", dest="input_format",
help=_("Input format, e.g. 'vmx'"))
cong.add_option("-o", "--output-format", dest="output_format",
cong.add_argument("-o", "--output-format", dest="output_format",
default="virt-image",
help=_("Output format, e.g. 'virt-image'"))
cong.add_option("-D", "--disk-format", dest="disk_format",
cong.add_argument("-D", "--disk-format", dest="disk_format",
help=_("Output disk format"))
opts.add_option_group(cong)
virg = OptionGroup(opts, "Virtualization Type Options")
virg.add_option("-v", "--hvm", action="store_true", dest="fullvirt",
virg = parser.add_argument_group("Virtualization Type Options")
virg.add_argument("-v", "--hvm", action="store_true", dest="fullvirt",
help=_("This guest should be a fully virtualized guest"))
virg.add_option("-p", "--paravirt", action="store_true", dest="paravirt",
virg.add_argument("-p", "--paravirt", action="store_true", dest="paravirt",
help=_("This guest should be a paravirtualized guest"))
opts.add_option_group(virg)
cfgg = OptionGroup(opts, "Guest Configuration Options")
cfgg.add_option("-a", "--arch", dest="arch",
cfgg = parser.add_argument_group("Guest Configuration Options")
cfgg.add_argument("-a", "--arch", dest="arch",
default=get_default_arch(),
help=_("Machine Architecture Type (i686/x86_64/ppc)"))
cli.add_distro_options(cfgg)
cli.add_old_feature_options(cfgg)
opts.add_option_group(cfgg)
misc = OptionGroup(opts, "Miscellaneous Options")
misc = parser.add_argument_group("Miscellaneous Options")
cli.add_misc_options(misc, dryrun=True)
opts.add_option_group(misc)
options, leftovers = parser.parse_known_args()
if options.input:
options.input = options.input[0]
(options, args) = opts.parse_args()
# argparse does not allow interspersed positional arguments, which we
# used to allow with optparse. All this crazyness is to keep old
# cli working
parser2 = argparse.ArgumentParser()
add_output_arg(parser2)
if not options.output:
opt2, leftovers = parser2.parse_known_args(leftovers)
options.output = opt2.output
if leftovers:
leftovers = sys.argv[:]
if options.output in leftovers:
leftovers.pop(leftovers.index(options.output))
if options.input in leftovers:
leftovers.pop(leftovers.index(options.input))
parser.parse_args(leftovers)
cli.setupLogging("virt-convert", options.debug, options.quiet)
if len(args) < 1:
opts.error(_("You need to provide an input VM definition"))
if len(args) > 2:
opts.error(_("Too many arguments provided"))
if (options.disk_format and
options.disk_format not in diskcfg.disk_formats()):
opts.error(_("Unknown output disk format \"%s\"") % options.disk_format)
parser.error(_("Unknown output disk format \"%s\"") %
options.disk_format)
if len(args) == 1:
if not options.output:
options.output_file = None
options.output_dir = None
if os.path.isdir(args[0]):
options.output_dir = args[0]
elif os.path.isdir(args[1]) or args[1].endswith("/"):
if os.path.isdir(options.input):
options.output_dir = options.input
elif os.path.isdir(options.output) or options.output.endswith("/"):
options.output_file = None
options.output_dir = args[1]
options.output_dir = options.output
else:
options.output_file = args[1]
options.output_dir = os.path.dirname(os.path.realpath(args[1]))
options.output_file = options.output
options.output_dir = os.path.dirname(os.path.realpath(options.output))
if options.output_format not in formats.formats():
opts.error(_("Unknown output format \"%s\")" % options.output_format))
parser.error(_("Unknown output format \"%s\")" %
options.output_format))
if options.output_format not in formats.output_formats():
opts.error(_("No output handler for format \"%s\")"
parser.error(_("No output handler for format \"%s\")"
% options.output_format))
if not os.access(args[0], os.R_OK):
opts.error(_("Couldn't access input argument \"%s\"\n") % args[0])
if not os.access(options.input, os.R_OK):
parser.error(_("Couldn't access input argument \"%s\"\n") % options.input)
sys.exit(1)
if not options.input_format:
try:
(args[0], options.input_format) = formats.find_input(args[0])
(options.input, options.input_format) = formats.find_input(options.input)
except StandardError, e:
opts.error(_("Couldn't determine input format for \"%s\": %s") %
(args[0], e))
parser.error(_("Couldn't determine input format for \"%s\": %s") %
(options.input, e))
sys.exit(1)
if options.input_format not in formats.formats():
opts.error(_("Unknown input format \"%s\")" % options.input_format))
parser.error(_("Unknown input format \"%s\")" % options.input_format))
if options.input_format not in formats.input_formats():
opts.error(_("No input handler for format \"%s\"")
parser.error(_("No input handler for format \"%s\"")
% options.input_format)
if os.path.isdir(args[0]):
(options.input_file, ignore) = formats.find_input(args[0],
if os.path.isdir(options.input):
(options.input_file, ignore) = formats.find_input(options.input,
options.input_format)
options.input_dir = args[0]
options.input_dir = options.input
else:
options.input_file = args[0]
options.input_dir = os.path.dirname(os.path.realpath(args[0]))
options.input_file = options.input
options.input_dir = os.path.dirname(os.path.realpath(options.input))
return options

View File

@ -20,7 +20,6 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA.
import optparse
import sys
import urlgrabber.progress as progress
@ -34,46 +33,41 @@ from virtinst import virtimage
### Option parsing
def parse_args():
parser = cli.setupParser(
"%prog image.xml [OPTIONS]",
"%(prog)s image.xml [OPTIONS]",
_("Create a virtual machine from a virt-image(5) image descriptor."))
cli.add_connect_option(parser)
geng = optparse.OptionGroup(parser, _("General Options"))
geng.add_option("-n", "--name", dest="name",
parser.add_argument("image", metavar="image.xml", nargs='?',
help=_("virt-image(5) image descriptor"))
geng = parser.add_argument_group(_("General Options"))
geng.add_argument("-n", "--name", dest="name",
help=_("Name of the guest instance"))
geng.add_option("-r", "--ram", type="int", dest="memory",
geng.add_argument("-r", "--ram", type=int, dest="memory",
help=_("Memory to allocate for guest instance in "
"megabytes"))
geng.add_option("-u", "--uuid", dest="uuid",
geng.add_argument("-u", "--uuid", dest="uuid",
help=_("UUID for the guest."))
cli.vcpu_cli_options(geng)
cli.add_distro_options(geng)
cli.add_old_feature_options(geng)
parser.add_option_group(geng)
netg = cli.network_option_group(parser)
parser.add_option_group(netg)
cli.network_option_group(parser)
cli.graphics_option_group(parser)
vncg = cli.graphics_option_group(parser)
parser.add_option_group(vncg)
misc = optparse.OptionGroup(parser, _("Miscellaneous Options"))
misc.add_option("--boot", type="int", dest="boot",
misc = parser.add_argument_group(_("Miscellaneous Options"))
misc.add_argument("--boot", type=int, dest="boot",
help=_("The zero-based index of the boot record to use"))
misc.add_option("--skip-checksum", action="store_true",
misc.add_argument("--skip-checksum", action="store_true",
dest="skipchecksum",
help=_("Skip disk checksum verification process"))
cli.add_misc_options(misc, prompt=True, replace=True, printxml=True,
noreboot=True)
parser.add_option_group(misc)
(options, args) = parser.parse_args()
if len(args) < 1:
options = parser.parse_args()
if not options.image:
parser.error(_("You need to provide an image XML descriptor"))
options.image = args[0]
return options

View File

@ -17,12 +17,12 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA.
import argparse
import logging
import os
import re
import sys
import time
import re
import logging
import optparse
import libvirt
import urlgrabber.progress as progress
@ -882,140 +882,131 @@ def xml_to_print(guest, continue_inst, xmlonly, xmlstep, dry):
def parse_args():
parser = cli.setupParser(
"%prog --name NAME --ram RAM STORAGE INSTALL [options]",
"%(prog)s --name NAME --ram RAM STORAGE INSTALL [options]",
_("Create a new virtual machine from specified install media."))
cli.add_connect_option(parser)
geng = optparse.OptionGroup(parser, _("General Options"))
geng.add_option("-n", "--name", dest="name",
geng = parser.add_argument_group(_("General Options"))
geng.add_argument("-n", "--name", dest="name",
help=_("Name of the guest instance"))
geng.add_option("-r", "--ram", type="int", dest="memory",
geng.add_argument("-r", "--ram", type=int, dest="memory",
help=_("Memory to allocate for guest instance in "
"megabytes"))
cli.vcpu_cli_options(geng)
geng.add_option("--description", dest="description",
geng.add_argument("--description", dest="description",
help=_("Human readable description of the VM to store in "
"the generated XML."))
geng.add_option("--security", dest="security",
geng.add_argument("--security", dest="security",
help=_("Set domain security driver configuration."))
geng.add_option("--numatune", dest="numatune",
geng.add_argument("--numatune", dest="numatune",
help=_("Tune NUMA policy for the domain process."))
geng.add_option("--features", dest="features",
geng.add_argument("--features", dest="features",
help=_("Set domain <features> XML. Ex:\n"
"--features acpi=off\n"
"--features apic=on,eoi=on"))
geng.add_option("--clock", dest="clock",
geng.add_argument("--clock", dest="clock",
help=_("Set domain <clock> XML. Ex:\n"
"--clock offset=localtime,rtc_tickpolicy=catchup"))
parser.add_option_group(geng)
insg = optparse.OptionGroup(parser, _("Installation Method Options"))
insg.add_option("-c", dest="cdrom_short", help=optparse.SUPPRESS_HELP)
insg.add_option("--cdrom", dest="cdrom",
insg = parser.add_argument_group(_("Installation Method Options"))
insg.add_argument("-c", dest="cdrom_short", help=argparse.SUPPRESS)
insg.add_argument("--cdrom", dest="cdrom",
help=_("CD-ROM installation media"))
insg.add_option("-l", "--location", dest="location",
insg.add_argument("-l", "--location", dest="location",
help=_("Installation source (eg, nfs:host:/path, "
"http://host/path, ftp://host/path)"))
insg.add_option("--pxe", action="store_true", dest="pxe",
insg.add_argument("--pxe", action="store_true", dest="pxe",
help=_("Boot from the network using the PXE protocol"))
insg.add_option("--import", action="store_true", dest="import_install",
insg.add_argument("--import", action="store_true", dest="import_install",
help=_("Build guest around an existing disk image"))
insg.add_option("--init", dest="init",
insg.add_argument("--init", dest="init",
help=_("Path to init binary for container guest. Ex:\n"
"--init /path/to/app (to contain an application)\n"
"--init /sbin/init (for a full OS container)"))
insg.add_option("--livecd", action="store_true", dest="livecd",
insg.add_argument("--livecd", action="store_true", dest="livecd",
help=_("Treat the CD-ROM media as a Live CD"))
insg.add_option("-x", "--extra-args", dest="extra",
insg.add_argument("-x", "--extra-args", dest="extra",
default="",
help=_("Additional arguments to pass to the install kernel "
"booted from --location"))
insg.add_option("--initrd-inject", dest="initrd_injections",
insg.add_argument("--initrd-inject", dest="initrd_injections",
action="append",
help=_("Add given file to root of initrd from --location"))
cli.add_distro_options(insg)
insg.add_option("--boot", dest="bootopts", default="",
insg.add_argument("--boot", dest="bootopts", default="",
help=_("Optionally configure post-install boot order, "
"menu, permanent kernel boot, etc."))
parser.add_option_group(insg)
stog = optparse.OptionGroup(parser, _("Storage Configuration"))
stog.add_option("--disk", dest="diskopts", action="append",
stog = parser.add_argument_group(_("Storage Configuration"))
stog.add_argument("--disk", dest="diskopts", action="append",
help=_("Specify storage with various options. Ex.\n"
"--disk path=/my/existing/disk\n"
"--disk path=/my/new/disk,size=5 (in gigabytes)\n"
"--disk vol=poolname/volname,device=cdrom,bus=scsi,..."))
stog.add_option("--nodisks", action="store_true",
stog.add_argument("--nodisks", action="store_true",
help=_("Don't set up any disks for the guest."))
cli.add_fs_option(stog)
# Deprecated storage options
stog.add_option("-f", "--file", dest="file_paths", action="append",
help=optparse.SUPPRESS_HELP)
stog.add_option("-s", "--file-size", type="float",
stog.add_argument("-f", "--file", dest="file_paths", action="append",
help=argparse.SUPPRESS)
stog.add_argument("-s", "--file-size", type=float,
action="append", dest="disksize",
help=optparse.SUPPRESS_HELP)
stog.add_option("--nonsparse", action="store_false",
help=argparse.SUPPRESS)
stog.add_argument("--nonsparse", action="store_false",
default=True, dest="sparse",
help=optparse.SUPPRESS_HELP)
parser.add_option_group(stog)
help=argparse.SUPPRESS)
netg = cli.network_option_group(parser)
netg.add_option("--nonetworks", action="store_true",
netg.add_argument("--nonetworks", action="store_true",
help=_("Don't create network interfaces for the guest."))
parser.add_option_group(netg)
vncg = cli.graphics_option_group(parser)
vncg.add_option("--noautoconsole", action="store_false",
vncg.add_argument("--noautoconsole", action="store_false",
dest="autoconsole", default=True,
help=_("Don't automatically try to connect to the guest "
"console"))
parser.add_option_group(vncg)
devg = optparse.OptionGroup(parser, _("Device Options"))
devg = parser.add_argument_group(_("Device Options"))
cli.add_device_options(devg)
# Deprecated
devg.add_option("--sound", action="store_true", dest="old_sound_bool",
default=False, help=optparse.SUPPRESS_HELP)
parser.add_option_group(devg)
devg.add_argument("--sound", action="store_true", dest="old_sound_bool",
default=False, help=argparse.SUPPRESS)
virg = optparse.OptionGroup(parser, _("Virtualization Platform Options"))
virg.add_option("-v", "--hvm", action="store_true", dest="fullvirt",
virg = parser.add_argument_group(_("Virtualization Platform Options"))
virg.add_argument("-v", "--hvm", action="store_true", dest="fullvirt",
help=_("This guest should be a fully virtualized guest"))
virg.add_option("-p", "--paravirt", action="store_true", dest="paravirt",
virg.add_argument("-p", "--paravirt", action="store_true", dest="paravirt",
help=_("This guest should be a paravirtualized guest"))
virg.add_option("--container", action="store_true", default=False,
virg.add_argument("--container", action="store_true", default=False,
dest="container",
help=_("This guest should be a container guest"))
virg.add_option("--virt-type", dest="hv_type",
virg.add_argument("--virt-type", dest="hv_type",
default="",
help=_("Hypervisor name to use (kvm, qemu, xen, ...)"))
virg.add_option("--accelerate", action="store_true", default=False,
dest="accelerate", help=optparse.SUPPRESS_HELP)
virg.add_option("--arch", dest="arch",
virg.add_argument("--accelerate", action="store_true", default=False,
dest="accelerate", help=argparse.SUPPRESS)
virg.add_argument("--arch", dest="arch",
help=_("The CPU architecture to simulate"))
virg.add_option("--machine", dest="machine",
virg.add_argument("--machine", dest="machine",
help=_("The machine type to emulate"))
virg.add_option("-u", "--uuid", dest="uuid",
virg.add_argument("-u", "--uuid", dest="uuid",
help=_("UUID for the guest."))
cli.add_old_feature_options(virg)
parser.add_option_group(virg)
misc = optparse.OptionGroup(parser, _("Miscellaneous Options"))
misc.add_option("--autostart", action="store_true", dest="autostart",
misc = parser.add_argument_group(_("Miscellaneous Options"))
misc.add_argument("--autostart", action="store_true", dest="autostart",
default=False,
help=_("Have domain autostart on host boot up."))
misc.add_option("--wait", type="int", dest="wait",
misc.add_argument("--wait", type=int, dest="wait",
help=_("Minutes to wait for install to complete."))
cli.add_misc_options(misc, prompt=True, printxml=True, printstep=True,
noreboot=True, dryrun=True)
parser.add_option_group(misc)
(options, cliargs) = parser.parse_args()
return options, cliargs
return parser.parse_args()
###################
@ -1024,15 +1015,13 @@ def parse_args():
def main(conn=None):
cli.earlyLogging()
options, cliargs = parse_args()
options = parse_args()
# Default setup options
options.quiet = options.xmlstep or options.xmlonly or options.quiet
cli.setupLogging("virt-install", options.debug, options.quiet)
if cliargs:
fail(_("Unknown argument '%s'") % cliargs[0])
check_cdrom_option_error(options)
if options.distro_variant == "list":

View File

@ -20,8 +20,8 @@
# MA 02110-1301 USA.
#
import argparse
import logging
import optparse
import os
import signal
import sys
@ -81,61 +81,47 @@ def drop_stdio():
os.dup2(0, 2)
class PassThroughOptionParser(optparse.OptionParser):
# From http://stackoverflow.com/questions/1885161/how-can-i-get-optparses-optionparser-to-ignore-invalid-options
def _process_args(self, largs, rargs, values):
while rargs:
try:
optparse.OptionParser._process_args(self, largs, rargs, values)
except (optparse.BadOptionError, optparse.AmbiguousOptionError), e:
largs.append(e.opt_str)
def parse_commandline():
optParser = PassThroughOptionParser(version=cliconfig.__version__,
usage="virt-manager [options]")
optParser.set_defaults(uuid=None)
optParser.epilog = ("Also accepts standard GTK arguments like "
"--g-fatal-warnings")
epilog = ("Also accepts standard GTK arguments like --g-fatal-warnings")
parser = argparse.ArgumentParser(usage="virt-manager [options]",
epilog=epilog)
parser.add_argument('--version', action='version',
version=cliconfig.__version__)
parser.set_defaults(uuid=None)
# Trace every libvirt API call to debug output
optParser.add_option("--trace-libvirt", dest="tracelibvirt",
help=optparse.SUPPRESS_HELP, action="store_true")
parser.add_argument("--trace-libvirt", dest="tracelibvirt",
help=argparse.SUPPRESS, action="store_true")
# Don't load any connections on startup to test first run
# PackageKit integration
optParser.add_option("--test-first-run", dest="testfirstrun",
help=optparse.SUPPRESS_HELP, action="store_true")
parser.add_argument("--test-first-run", dest="testfirstrun",
help=argparse.SUPPRESS, action="store_true")
optParser.add_option("-c", "--connect", dest="uri",
parser.add_argument("-c", "--connect", dest="uri",
help="Connect to hypervisor at URI", metavar="URI")
optParser.add_option("--debug", action="store_true", dest="debug",
parser.add_argument("--debug", action="store_true", dest="debug",
help="Print debug output to stdout (implies --no-fork)",
default=False)
optParser.add_option("--no-fork", action="store_true", dest="nofork",
parser.add_argument("--no-fork", action="store_true", dest="nofork",
help="Don't fork into background on startup")
optParser.add_option("--no-conn-autostart", action="store_true",
dest="no_conn_auto",
help="Do not autostart connections")
parser.add_argument("--no-conn-autostart", action="store_true",
dest="no_conn_auto", help="Do not autostart connections")
parser.add_argument("--spice-disable-auto-usbredir", action="store_true",
dest="usbredir", help="Disable Auto USB redirection support")
optParser.add_option("--show-domain-creator", action="callback",
callback=opt_show_cb, dest="show",
parser.add_argument("--show-domain-creator", action="store_true",
help="Show 'New VM' wizard")
optParser.add_option("--show-domain-editor", type="string",
metavar="UUID", action="callback", callback=opt_show_cb,
parser.add_argument("--show-domain-editor", metavar="UUID",
help="Show domain details window")
optParser.add_option("--show-domain-performance", type="string",
metavar="UUID", action="callback", callback=opt_show_cb,
parser.add_argument("--show-domain-performance", metavar="UUID",
help="Show domain performance window")
optParser.add_option("--show-domain-console", type="string",
metavar="UUID", action="callback", callback=opt_show_cb,
parser.add_argument("--show-domain-console", metavar="UUID",
help="Show domain graphical console window")
optParser.add_option("--show-host-summary", action="callback",
callback=opt_show_cb, help="Show connection details window")
optParser.add_option("--spice-disable-auto-usbredir", action="store_true",
dest="usbredir", help="Disable Auto USB redirection support")
parser.add_argument("--show-host-summary", action="store_true",
help="Show connection details window")
return optParser.parse_args()
return parser.parse_known_args()
def launch_specific_window(engine, show, uri, uuid):
@ -155,17 +141,6 @@ def launch_specific_window(engine, show, uri, uuid):
engine.show_host_summary(uri)
def opt_show_cb(option, opt_str, value, parser):
# Generic OptionParser callback for all --show-* options
# This routine stores UUID to options.uuid for all --show-* options
# where is metavar="UUID" and also sets options.show
if option.metavar == "UUID":
setattr(parser.values, "uuid", value)
s = str(option)
show = s[s.rindex('-') + 1:]
setattr(parser.values, "show", show)
def main():
cliutils.setup_i18n()
(options, leftovers) = parse_commandline()
@ -255,9 +230,26 @@ def main():
Gtk.Window.set_default_icon_name("virt-manager")
if options.show and options.uri is None:
raise optparse.OptionValueError("can't use --show-* options "
"without --connect")
show = None
if options.show_domain_creator:
show = "creator"
elif options.show_domain_editor:
show = "editor"
elif options.show_domain_performance:
show = "performance"
elif options.show_domain_console:
show = "console"
elif options.show_host_summary:
show = "summary"
if show and options.uri is None:
raise RuntimeError("can't use --show-* options without --connect")
if show:
options.uuid = (options.uuid or options.show_domain_creator or
options.show_domain_editor or
options.show_domain_performance or
options.show_domain_console or
options.show_host_summary)
# Hook libvirt events into glib main loop
LibvirtGLib.init(None)
@ -267,11 +259,10 @@ def main():
engine.skip_autostart = options.no_conn_auto
engine.uri_at_startup = options.uri
if options.show:
if show:
def cb(conn):
ignore = conn
launch_specific_window(engine,
options.show, options.uri, options.uuid)
launch_specific_window(engine, show, options.uri, options.uuid)
return True
engine.uri_cb = cb
engine.show_manager_window = False

View File

@ -19,10 +19,9 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA.
import locale
import argparse
import logging
import logging.handlers
import optparse
import os
import shlex
import sys
@ -70,70 +69,41 @@ class VirtStreamHandler(logging.StreamHandler):
self.handleError(record)
class VirtOptionParser(optparse.OptionParser):
'''Subclass to get print_help to work properly with non-ascii text'''
def _get_encoding(self, f):
encoding = getattr(f, "encoding", None)
if not encoding:
encoding = locale.getlocale()[1]
if not encoding:
encoding = "UTF-8"
return encoding
def print_help(self, file=None):
# pylint: disable=W0622
# Redefining built in type 'file'
if file is None:
file = sys.stdout
encoding = self._get_encoding(file)
helpstr = self.format_help()
try:
encodedhelp = helpstr.encode(encoding, "replace")
except UnicodeError:
# I don't know why the above fails hard, unicode makes my head
# spin. Just printing the format_help() output seems to work
# quite fine, with the occasional character ?.
encodedhelp = helpstr
file.write(encodedhelp)
class VirtHelpFormatter(optparse.IndentedHelpFormatter):
"""
class VirtHelpFormatter(argparse.HelpFormatter):
'''
Subclass the default help formatter to allow printing newline characters
in --help output. The way we do this is a huge hack :(
Inspiration: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6df6e6b541a15bc2/09f28e26af0699b1
"""
'''
oldwrap = None
def format_option(self, option):
self.oldwrap = optparse.textwrap.wrap
ret = []
try:
optparse.textwrap.wrap = self._textwrap_wrapper
ret = optparse.IndentedHelpFormatter.format_option(self, option)
finally:
optparse.textwrap.wrap = self.oldwrap
return ret
def _split_lines(self, *args, **kwargs):
def return_default():
return argparse.HelpFormatter._split_lines(self, *args, **kwargs)
def _textwrap_wrapper(self, text, width):
ret = []
for line in text.split("\n"):
ret.extend(self.oldwrap(line, width))
return ret
if len(kwargs) != 0 and len(args) != 2:
return return_default()
try:
text = args[0]
if "\n" in text:
return text.splitlines()
return return_default()
except:
return return_default()
def setupParser(usage, description):
parse_class = VirtOptionParser
parse_class = argparse.ArgumentParser
epilog = _("See man page for examples and full option syntax.")
parser = parse_class(usage=usage, description=description,
formatter=VirtHelpFormatter(),
version=cliconfig.__version__)
parser.epilog = _("See man page for examples and full option syntax.")
parser = argparse.ArgumentParser(
usage=usage, description=description,
formatter_class=VirtHelpFormatter,
epilog=epilog)
parser.add_argument('--version', action='version',
version=cliconfig.__version__)
return parser
@ -783,7 +753,7 @@ def set_os_variant(obj, distro_type, distro_variant):
#############################
def add_connect_option(parser):
parser.add_option("--connect", metavar="URI", dest="connect",
parser.add_argument("--connect", metavar="URI", dest="connect",
help=_("Connect to hypervisor with libvirt URI"))
@ -791,54 +761,54 @@ def add_misc_options(grp, prompt=False, replace=False,
printxml=False, printstep=False,
noreboot=False, dryrun=False):
if prompt:
grp.add_option("--prompt", action="store_true", dest="prompt",
default=False, help=optparse.SUPPRESS_HELP)
grp.add_option("--force", action="store_true", dest="force",
default=False, help=optparse.SUPPRESS_HELP)
grp.add_argument("--prompt", action="store_true", dest="prompt",
default=False, help=argparse.SUPPRESS)
grp.add_argument("--force", action="store_true", dest="force",
default=False, help=argparse.SUPPRESS)
if noreboot:
grp.add_option("--noreboot", action="store_true", dest="noreboot",
grp.add_argument("--noreboot", action="store_true", dest="noreboot",
help=_("Don't boot guest after completing install."))
if replace:
grp.add_option("--replace", action="store_true", dest="replace",
grp.add_argument("--replace", action="store_true", dest="replace",
help=_("Don't check name collision, overwrite any guest "
"with the same name."))
if printxml:
grp.add_option("--print-xml", action="store_true", dest="xmlonly",
grp.add_argument("--print-xml", action="store_true", dest="xmlonly",
help=_("Print the generated domain XML rather than define "
"and clone the guest."))
if printstep:
grp.add_option("--print-step", type="str", dest="xmlstep",
grp.add_argument("--print-step", dest="xmlstep",
help=_("Print XML of a specific install step "
"(1, 2, 3, all) rather than define the guest."))
if dryrun:
grp.add_option("--dry-run", action="store_true", dest="dry",
grp.add_argument("--dry-run", action="store_true", dest="dry",
help=_("Run through install process, but do not "
"create devices or define the guest."))
grp.add_option("-q", "--quiet", action="store_true", dest="quiet",
grp.add_argument("-q", "--quiet", action="store_true", dest="quiet",
help=_("Suppress non-error output"))
grp.add_option("-d", "--debug", action="store_true", dest="debug",
grp.add_argument("-d", "--debug", action="store_true", dest="debug",
help=_("Print debugging information"))
def vcpu_cli_options(grp, backcompat=True):
grp.add_option("--vcpus", dest="vcpus",
grp.add_argument("--vcpus", dest="vcpus",
help=_("Number of vcpus to configure for your guest. Ex:\n"
"--vcpus 5\n"
"--vcpus 5,maxcpus=10\n"
"--vcpus sockets=2,cores=4,threads=2"))
grp.add_option("--cpuset", dest="cpuset",
grp.add_argument("--cpuset", dest="cpuset",
help=_("Set which physical CPUs domain can use."))
grp.add_option("--cpu", dest="cpu",
grp.add_argument("--cpu", dest="cpu",
help=_("CPU model and features. Ex: --cpu coreduo,+x2apic"))
if backcompat:
grp.add_option("--check-cpu", action="store_true",
dest="check_cpu", help=optparse.SUPPRESS_HELP)
grp.add_argument("--check-cpu", action="store_true",
dest="check_cpu", help=argparse.SUPPRESS)
def graphics_option_group(parser):
@ -846,20 +816,20 @@ def graphics_option_group(parser):
Register vnc + sdl options for virt-install and virt-image
"""
vncg = optparse.OptionGroup(parser, _("Graphics Configuration"))
vncg = parser.add_argument_group(_("Graphics Configuration"))
add_gfx_option(vncg)
vncg.add_option("--vnc", action="store_true", dest="vnc",
help=optparse.SUPPRESS_HELP)
vncg.add_option("--vncport", type="int", dest="vncport",
help=optparse.SUPPRESS_HELP)
vncg.add_option("--vnclisten", dest="vnclisten",
help=optparse.SUPPRESS_HELP)
vncg.add_option("-k", "--keymap", dest="keymap",
help=optparse.SUPPRESS_HELP)
vncg.add_option("--sdl", action="store_true", dest="sdl",
help=optparse.SUPPRESS_HELP)
vncg.add_option("--nographics", action="store_true",
help=optparse.SUPPRESS_HELP)
vncg.add_argument("--vnc", action="store_true", dest="vnc",
help=argparse.SUPPRESS)
vncg.add_argument("--vncport", type=int, dest="vncport",
help=argparse.SUPPRESS)
vncg.add_argument("--vnclisten", dest="vnclisten",
help=argparse.SUPPRESS)
vncg.add_argument("-k", "--keymap", dest="keymap",
help=argparse.SUPPRESS)
vncg.add_argument("--sdl", action="store_true", dest="sdl",
help=argparse.SUPPRESS)
vncg.add_argument("--nographics", action="store_true",
help=argparse.SUPPRESS)
return vncg
@ -867,21 +837,21 @@ def network_option_group(parser):
"""
Register common network options for virt-install and virt-image
"""
netg = optparse.OptionGroup(parser, _("Networking Configuration"))
netg = parser.add_argument_group(_("Networking Configuration"))
add_net_option(netg)
# Deprecated net options
netg.add_option("-b", "--bridge", dest="bridge", action="append",
help=optparse.SUPPRESS_HELP)
netg.add_option("-m", "--mac", dest="mac", action="append",
help=optparse.SUPPRESS_HELP)
netg.add_argument("-b", "--bridge", dest="bridge", action="append",
help=argparse.SUPPRESS)
netg.add_argument("-m", "--mac", dest="mac", action="append",
help=argparse.SUPPRESS)
return netg
def add_net_option(devg):
devg.add_option("-w", "--network", dest="network", action="append",
devg.add_argument("-w", "--network", dest="network", action="append",
help=_("Configure a guest network interface. Ex:\n"
"--network bridge=mybr0\n"
"--network network=my_libvirt_virtual_net\n"
@ -890,47 +860,47 @@ def add_net_option(devg):
def add_device_options(devg):
devg.add_option("--controller", dest="controller", action="append",
devg.add_argument("--controller", dest="controller", action="append",
help=_("Configure a guest controller device. Ex:\n"
"--controller type=usb,model=ich9-ehci1"))
devg.add_option("--serial", dest="serials", action="append",
devg.add_argument("--serial", dest="serials", action="append",
help=_("Configure a guest serial device"))
devg.add_option("--parallel", dest="parallels", action="append",
devg.add_argument("--parallel", dest="parallels", action="append",
help=_("Configure a guest parallel device"))
devg.add_option("--channel", dest="channels", action="append",
devg.add_argument("--channel", dest="channels", action="append",
help=_("Configure a guest communication channel"))
devg.add_option("--console", dest="consoles", action="append",
devg.add_argument("--console", dest="consoles", action="append",
help=_("Configure a text console connection between "
"the guest and host"))
devg.add_option("--host-device", dest="hostdevs", action="append",
devg.add_argument("--host-device", dest="hostdevs", action="append",
help=_("Configure physical host devices attached to the "
"guest"))
devg.add_option("--soundhw", dest="sound", action="append",
devg.add_argument("--soundhw", dest="sound", action="append",
help=_("Configure guest sound device emulation"))
devg.add_option("--watchdog", dest="watchdog", action="append",
devg.add_argument("--watchdog", dest="watchdog", action="append",
help=_("Configure a guest watchdog device"))
devg.add_option("--video", dest="video", action="append",
devg.add_argument("--video", dest="video", action="append",
help=_("Configure guest video hardware."))
devg.add_option("--smartcard", dest="smartcard", action="append",
devg.add_argument("--smartcard", dest="smartcard", action="append",
help=_("Configure a guest smartcard device. Ex:\n"
"--smartcard mode=passthrough"))
devg.add_option("--redirdev", dest="redirdev", action="append",
devg.add_argument("--redirdev", dest="redirdev", action="append",
help=_("Configure a guest redirection device. Ex:\n"
"--redirdev usb,type=tcp,server=192.168.1.1:4000"))
devg.add_option("--memballoon", dest="memballoon", action="append",
devg.add_argument("--memballoon", dest="memballoon", action="append",
help=_("Configure a guest memballoon device. Ex:\n"
"--memballoon model=virtio"))
devg.add_option("--tpm", dest="tpm", action="append",
devg.add_argument("--tpm", dest="tpm", action="append",
help=_("Configure a guest TPM device. Ex:\n"
"--tpm /dev/tpm"))
devg.add_option("--rng", dest="rng", action="append",
devg.add_argument("--rng", dest="rng", action="append",
help=_("Configure a guest RNG device. Ex:\n"
"--rng /dev/random\n"
"--rng egd,backend_host=localhost,backend_service=708,backend_type=tcp"))
def add_gfx_option(devg):
devg.add_option("--graphics", dest="graphics", action="append",
devg.add_argument("--graphics", dest="graphics", action="append",
help=_("Configure guest display settings. Ex:\n"
"--graphics vnc\n"
"--graphics spice,port=5901,tlsport=5902\n"
@ -939,7 +909,7 @@ def add_gfx_option(devg):
def add_fs_option(devg):
devg.add_option("--filesystem", dest="filesystems", action="append",
devg.add_argument("--filesystem", dest="filesystems", action="append",
help=_("Pass host directory to the guest. Ex: \n"
"--filesystem /my/source/dir,/dir/in/guest\n"
"--filesystem template_name,/,type=template"))
@ -949,18 +919,18 @@ def add_distro_options(g):
# Way back when, we required specifying both --os-type and --os-variant
# Nowadays the distinction is pointless, so hide the less useful
# --os-type option.
g.add_option("--os-type", dest="distro_type",
help=optparse.SUPPRESS_HELP)
g.add_option("--os-variant", dest="distro_variant",
g.add_argument("--os-type", dest="distro_type",
help=argparse.SUPPRESS)
g.add_argument("--os-variant", dest="distro_variant",
help=_("The OS variant being installed guests, "
"e.g. 'fedora18', 'rhel6', 'winxp', etc."))
def add_old_feature_options(optg):
optg.add_option("--noapic", action="store_true", dest="noapic",
default=False, help=optparse.SUPPRESS_HELP)
optg.add_option("--noacpi", action="store_true", dest="noacpi",
default=False, help=optparse.SUPPRESS_HELP)
optg.add_argument("--noapic", action="store_true", dest="noapic",
default=False, help=argparse.SUPPRESS)
optg.add_argument("--noacpi", action="store_true", dest="noacpi",
default=False, help=argparse.SUPPRESS)
#############################################