sys.argv.append

Here are the examples of the python api sys.argv.append taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

120 Examples 7

Example 1

Project: cyg-apt
Source File: test_argparser.py
View license
    def testArgumentType(self):
        sys.argv.append("--mirror=http://a.mirror.str");
        sys.argv.append("update");
        sys.argv.append("--dist=test");

        ret = self.obj.parse();

        self.assertEqual("test", ret.distname);
        self.assertEqual("http://a.mirror.str", ret.mirror);

Example 2

Project: mownfish
Source File: test_config.py
View license
    def setUp(self):
        self.test_path = os.path.split(os.path.realpath(__file__))[0]
        self.test_config_file = os.path.join(self.test_path, 'etc',
                                             'mownfish.conf')
        self.test_log_path = os.path.join(self.test_path, 'log')
        sys.argv.append('--cfg_file=%s' % self.test_config_file)
        sys.argv.append('--port=8086')
        os.mkdir(self.test_log_path)
        sys.argv.append('--log_path=%s' % self.test_log_path)

Example 3

Project: kover
Source File: command_line.py
View license
    def create(self):
        creation_tool = KoverDatasetCreationTool()

        parser = argparse.ArgumentParser(usage= \
'''%(prog)s dataset create <data source> [<args>]
The two available data sources are:
    from-tsv     Create a Kover dataset from genomic data in a tsv format
    from-contigs      Create a Kover dataset from contigs''')

        parser.add_argument('datasource', help='The type of genomic data to be used.',
                            choices=creation_tool.available_data_sources)

        # If no argument has been specified, default to help
        if len(argv) == 3:
            argv.append("--help")

        args = parser.parse_args(argv[3:4])
        args.datasource = args.datasource.replace("-", "_")
        getattr(creation_tool, args.datasource)()

Example 4

View license
    @mock.patch('os_cloud_config.neutron.initialize_neutron')
    @mock.patch.dict('os.environ', {'OS_USERNAME': 'a', 'OS_PASSWORD': 'a',
                     'OS_TENANT_NAME': 'a', 'OS_AUTH_URL': 'a'})
    @mock.patch.object(sys, 'argv', ['setup-neutron', '--network-json'])
    def test_with_exception(self, initialize_mock):
        initialize_mock.side_effect = ValueError
        with tempfile.NamedTemporaryFile() as f:
            f.write('{}\n'.encode('utf-8'))
            f.flush()
            sys.argv.append(f.name)
            return_code = setup_neutron.main()
        self.assertEqual(1, return_code)

Example 5

View license
    @mock.patch('os_cloud_config.nodes.register_all_nodes')
    @mock.patch.dict('os.environ', {'OS_USERNAME': 'a', 'OS_PASSWORD': 'a',
                     'OS_TENANT_NAME': 'a', 'OS_AUTH_URL': 'a'})
    @mock.patch.object(sys, 'argv', ['register-nodes', '--service-host',
                       'seed', '--nodes'])
    def test_with_exception(self, register_mock):
        register_mock.side_effect = ValueError
        with tempfile.NamedTemporaryFile() as f:
            f.write(u'{}\n'.encode('utf-8'))
            f.flush()
            sys.argv.append(f.name)
            return_code = register_nodes.main()
        self.assertEqual(1, return_code)

Example 6

Project: cyg-apt
Source File: test_argparser.py
View license
    @dataProvider('getParseCommandData')
    def testParseCommand(self, command, args=None):
        """
        @param command: str
        @param args:    list
        """
        if None is args :
            args = list();

        sys.argv.append(command);
        for arg in args :
            sys.argv.append(arg);

        ret = self.obj.parse();

        self.assertEqual(ret.command, command);
        self.assertEqual(ret.package, args);

Example 7

Project: crumbs
Source File: test_unit.py
View license
    def test_parse_only_known_with_help(self):
        '''Parameters().parse(only_known = True)—with --help'''

        sys.argv.append('--help')
        self.addCleanup(functools.partial(sys.argv.remove, '--help'))

        self.p.parse(only_known = True)

        self.assertFalse(self.p.parsed)

Example 8

Project: PyAutoC
Source File: argvemulator.py
View license
    def __openfiles(self, requestevent, replyevent):
        try:
            listdesc = requestevent.AEGetParamDesc(keyDirectObject, typeAEList)
            for i in range(listdesc.AECountItems()):
                aliasdesc = listdesc.AEGetNthDesc(i+1, typeAlias)[1]
                alias = File.Alias(rawdata=aliasdesc.data)
                fsref = alias.FSResolveAlias(None)[0]
                pathname = fsref.as_pathname()
                sys.argv.append(pathname)
        except  Exception, e:
            print "argvemulator.py warning: can't unpack an open document event"
            import traceback
            traceback.print_exc()

        self._quit()

Example 9

Project: cyg-apt
Source File: test_argparser.py
View license
    def testNoPostInstallOptionIsDeprecated(self):
        sys.argv.append("-y");

        ret = self._assertDeprecatedWarning(
            "The option -y, --nopostinstall is deprecated since version "
            "1.1 and will be removed in 2.0.",
            self.obj.parse
        );

        self.assertTrue(ret.nopostinstall);

Example 10

Project: python-for-android
Source File: toolchain.py
View license
    def _read_configuration(self):
        # search for a .p4a configuration file in the current directory
        if not exists(".p4a"):
            return
        info("Reading .p4a configuration")
        with open(".p4a") as fd:
            lines = fd.readlines()
        lines = [shlex.split(line)
                 for line in lines if not line.startswith("#")]
        for line in lines:
            for arg in line:
                sys.argv.append(arg)

Example 11

Project: python-for-android
Source File: toolchain.py
View license
    def _read_configuration(self):
        # search for a .p4a configuration file in the current directory
        if not exists(".p4a"):
            return
        info("Reading .p4a configuration")
        with open(".p4a") as fd:
            lines = fd.readlines()
        lines = [shlex.split(line)
                 for line in lines if not line.startswith("#")]
        for line in lines:
            for arg in line:
                sys.argv.append(arg)

Example 12

Project: pyafipws
Source File: wscdc.py
View license
    def setUp(self):
        sys.argv.append("--trace")                  # TODO: use logging
        self.wscdc = wslpg = WSCDC()
        wslpg.LanzarExcepciones = True
        wslpg.Conectar(wsdl=WSDL, cacert=None, cache=CACHE)
        wslpg.Cuit = CUIT
        wslpg.Token = wsaa.Token
        wslpg.Sign = wsaa.Sign                    

Example 13

Project: gmvault
Source File: conf_tests.py
View license
    def test_print_content(self):
        """ test print content """
        
        #set environment
        os.environ["TESTENV"] = "/tmp/foo/foo.bar"
        
        #set cli arg
        sys.argv.append("--LongName")
        sys.argv.append("My Cli Value")
        
        substitute_values = True
        
        result = self.conf.print_content( substitute_values )
        
        self.assertNotEqual(result, '')

Example 14

Project: ibid
Source File: __init__.py
View license
def run():
    "Run the Ibid test suite. Bit of a hack"
    from twisted.scripts.trial import run
    import sys
    sys.argv.append('ibid')
    run()

Example 15

Project: pymssql
Source File: run_sqlalchemy_tests.py
View license
def run_sqlalchemy_tests():
    dburi = get_dburi()

    if dburi:
        sys.argv.append('--dburi=%s' % dburi)

    os.chdir('SQLAlchemy-%s' % SQLALCHEMY_VERSION)
    sys.path.append('.')
    sys.stdout.write('Running SQLAlchemy tests...\n\n')
    sys.stdout.flush()

    import sqla_nose

Example 16

Project: cyg-apt
Source File: test_argparser.py
View license
    def testMd5CommandIsDeprecated(self):
        sys.argv.append("md5");

        ret = self._assertDeprecatedWarning(
            "The command md5 is deprecated since version 1.2 and will be "
            "removed in 2.0, use checksum instead.",
            self.obj.parse
        );

        self.assertEqual(ret.command, "checksum");

Example 17

Project: kover
Source File: command_line.py
View license
    def dataset(self):
        dataset_tool = KoverDatasetTool()

        parser = argparse.ArgumentParser(usage= \
'''%(prog)s dataset <command> [<args>]
The most commonly used commands are:
    create     Create Kover datasets from genomic data
    split      Split a Kover dataset file into a training set, a testing set and optionally cross-validation folds
    info       Get information about the content of a Kover dataset''')

        parser.add_argument('command', help='The dataset manipulation to perform',
                            choices=dataset_tool.available_commands)

        # If no argument has been specified, default to help
        if len(argv) == 2:
            argv.append("--help")

        args = parser.parse_args(argv[2:3])
        getattr(dataset_tool, args.command)()

Example 18

Project: cyg-apt
Source File: test_argparser.py
View license
    def testParse(self):
        sys.argv.append("install");
        sys.argv.append("pkg");

        ret = self.obj.parse();

        self.assertTrue(ret.verbose);
        self.assertEqual(ret.command, "install");
        self.assertEqual(ret.package, ['pkg']);

Example 19

Project: crumbs
Source File: test_unit.py
View license
    def test_parse_with_help(self):
        '''Parameters().parse()—with --help'''

        sys.argv.append('--help')
        self.addCleanup(functools.partial(sys.argv.remove, '--help'))

        with self.assertRaises(SystemExit):
            self.p.parse()

Example 20

Project: cyg-apt
Source File: test_argparser.py
View license
    def testNoPostRemoveOptionIsDeprecated(self):
        sys.argv.append("-z");

        ret = self._assertDeprecatedWarning(
            "The option -z, --nopostremove is deprecated since version "
            "1.1 and will be removed in 2.0.",
            self.obj.parse
        );

        self.assertTrue(ret.nopostremove);

Example 21

Project: gmvault
Source File: conf_tests.py
View license
    def test_resource_simple_cli(self):
        """testResourceSimpleCli: read resource from CLI"""
        # set command line
        sys.argv.append("--LongName")
        sys.argv.append("My Cli Value")
        
        resource = gmv.conf.conf_helper.Resource(a_cli_argument = "--LongName", a_env_variable = None) 
        
        self.assertEqual("My Cli Value", resource.get_value())
        
        # look for LongName without --. It should be formalized by the Resource object
        resource = gmv.conf.conf_helper.Resource(a_cli_argument = "LongName", a_env_variable = None) 
        
        self.assertEqual("My Cli Value", resource.get_value())

Example 22

Project: pyafipws
Source File: wslpg.py
View license
    def setUp(self):
        sys.argv.append("--trace")                  # TODO: use logging
        self.wslpg = wslpg = WSLPG()
        wslpg.LanzarExcepciones = True
        wslpg.Conectar(url=WSDL, cacert=None, cache=CACHE)
        wslpg.Cuit = CUIT
        wslpg.Token = wsaa.Token
        wslpg.Sign = wsaa.Sign                    

Example 23

Project: cylc
Source File: task_message.py
View license
    def _send_by_ssh(self):
        """Send message via SSH."""
        self._load_suite_contact_file()

        # The suite definition specified that this task should
        # communicate back to the suite by means of using
        # non-interactive ssh to re-invoke the messaging command on the
        # suite host.

        # The remote_run() function expects command line options
        # to identify the target user and host names:
        sys.argv.append('--user=' + self.owner)
        sys.argv.append('--host=' + self.host)
        if cylc.flags.verbose:
            sys.argv.append('-v')

        if self.ssh_login_shell:
            sys.argv.append('--login')
        else:
            sys.argv.append('--no-login')

        # Some variables from the task execution environment are
        # also required by the re-invoked remote command: Note that
        # $CYLC_TASK_SSH_MESSAGING is not passed through so the
        # re-invoked command on the remote side will not end up in
        # this code block.
        env = {}
        for var in [
                'CYLC_MODE', 'CYLC_TASK_ID', 'CYLC_VERBOSE',
                'CYLC_SUITE_DEF_PATH_ON_SUITE_HOST',
                'CYLC_SUITE_RUN_DIR',
                'CYLC_SUITE_NAME', 'CYLC_SUITE_OWNER',
                'CYLC_SUITE_HOST', 'CYLC_SUITE_PORT', 'CYLC_UTC',
                'CYLC_TASK_MSG_MAX_TRIES', 'CYLC_TASK_MSG_TIMEOUT',
                'CYLC_TASK_MSG_RETRY_INTVL']:
            # (no exception handling here as these variables should
            # always be present in the task execution environment)
            env[var] = self.env_map.get(var, 'UNSET')

        # The path to cylc/bin on the remote end may be required:
        path = os.path.join(self.env_map['CYLC_DIR_ON_SUITE_HOST'], 'bin')

        # Return here if remote re-invocation occurred,
        # otherwise drop through to local messaging.
        # Note: do not sys.exit(0) here as the commands do, it
        # will cause messaging failures on the remote host.
        try:
            return remrun().execute(env=env, path=[path])
        except SystemExit:
            return

Example 24

Project: python-for-android
Source File: bdistapk.py
View license
    def finalize_options(self):

        setup_options = self.distribution.get_option_dict('apk')
        for (option, (source, value)) in setup_options.items():
            if source == 'command line':
                continue
            if not argv_contains('--' + option):
                # allow 'permissions': ['permission', 'permission] in apk
                if option == 'permissions':
                    for perm in value:
                        sys.argv.append('--permission={}'.format(perm))
                elif value in (None, 'None'):
                    sys.argv.append('--{}'.format(option))
                else:
                    sys.argv.append('--{}={}'.format(option, value))

        # Inject some argv options from setup.py if the user did not
        # provide them
        if not argv_contains('--name'):
            name = self.distribution.get_name()
            sys.argv.append('--name="{}"'.format(name))
            self.name = name

        if not argv_contains('--package'):
            package = 'org.test.{}'.format(self.name.lower().replace(' ', ''))
            print('WARNING: You did not supply an Android package '
                  'identifier, trying {} instead.'.format(package))
            print('         This may fail if this is not a valid identifier')
            sys.argv.append('--package={}'.format(package))

        if not argv_contains('--version'):
            version = self.distribution.get_version()
            sys.argv.append('--version={}'.format(version))

        if not argv_contains('--arch'):
            arch = 'armeabi'
            self.arch = arch
            sys.argv.append('--arch={}'.format(arch))

Example 25

Project: python-for-android
Source File: bdistapk.py
View license
    def finalize_options(self):

        setup_options = self.distribution.get_option_dict('apk')
        for (option, (source, value)) in setup_options.items():
            if source == 'command line':
                continue
            if not argv_contains('--' + option):
                # allow 'permissions': ['permission', 'permission] in apk
                if option == 'permissions':
                    for perm in value:
                        sys.argv.append('--permission={}'.format(perm))
                elif value in (None, 'None'):
                    sys.argv.append('--{}'.format(option))
                else:
                    sys.argv.append('--{}={}'.format(option, value))

        # Inject some argv options from setup.py if the user did not
        # provide them
        if not argv_contains('--name'):
            name = self.distribution.get_name()
            sys.argv.append('--name="{}"'.format(name))
            self.name = name

        if not argv_contains('--package'):
            package = 'org.test.{}'.format(self.name.lower().replace(' ', ''))
            print('WARNING: You did not supply an Android package '
                  'identifier, trying {} instead.'.format(package))
            print('         This may fail if this is not a valid identifier')
            sys.argv.append('--package={}'.format(package))

        if not argv_contains('--version'):
            version = self.distribution.get_version()
            sys.argv.append('--version={}'.format(version))

        if not argv_contains('--arch'):
            arch = 'armeabi'
            self.arch = arch
            sys.argv.append('--arch={}'.format(arch))

Example 26

Project: chipsec
Source File: test_dist.py
View license
    def test_command_packages_unspecified(self):
        sys.argv.append("build")
        d = self.create_distribution()
        self.assertEqual(d.get_command_packages(), ["distutils.command"])

Example 27

Project: chipsec
Source File: test_dist.py
View license
    def test_debug_mode(self):
        with open(TESTFN, "w") as f:
            f.write("[global]")
            f.write("command_packages = foo.bar, splat")

        files = [TESTFN]
        sys.argv.append("build")

        with captured_stdout() as stdout:
            self.create_distribution(files)
        stdout.seek(0)
        self.assertEqual(stdout.read(), '')
        distutils.dist.DEBUG = True
        try:
            with captured_stdout() as stdout:
                self.create_distribution(files)
            stdout.seek(0)
            self.assertEqual(stdout.read(), '')
        finally:
            distutils.dist.DEBUG = False

Example 28

Project: downstream-farmer
Source File: test_unit.py
View license
    def test_parse_args_path(self):
        sys.argv.append('--history')
        sys.argv.append('testpath')
        args = shell.parse_args()
        self.assertEqual(args.history, sys.argv[2])

Example 29

Project: imagrium
Source File: test_dist.py
View license
    def test_debug_mode(self):
        with open(TESTFN, "w") as f:
            f.write("[global]\n")
            f.write("command_packages = foo.bar, splat")

        files = [TESTFN]
        sys.argv.append("build")

        with captured_stdout() as stdout:
            self.create_distribution(files)
        stdout.seek(0)
        self.assertEqual(stdout.read(), '')
        distutils.dist.DEBUG = True
        try:
            with captured_stdout() as stdout:
                self.create_distribution(files)
            stdout.seek(0)
            self.assertEqual(stdout.read(), '')
        finally:
            distutils.dist.DEBUG = False

Example 30

Project: downstream-farmer
Source File: test_unit.py
View license
    def test_parse_args_size(self):
        sys.argv.append('--size')
        sys.argv.append('10')
        args = shell.parse_args()
        self.assertEqual(args.size, int(sys.argv[2]))

Example 31

Project: chipsec
Source File: test_dist.py
View license
    def test_command_packages_configfile(self):
        sys.argv.append("build")
        self.addCleanup(os.unlink, TESTFN)
        f = open(TESTFN, "w")
        try:
            print >>f, "[global]"
            print >>f, "command_packages = foo.bar, splat"
        finally:
            f.close()

        d = self.create_distribution([TESTFN])
        self.assertEqual(d.get_command_packages(),
                         ["distutils.command", "foo.bar", "splat"])

        # ensure command line overrides config:
        sys.argv[1:] = ["--command-packages", "spork", "build"]
        d = self.create_distribution([TESTFN])
        self.assertEqual(d.get_command_packages(),
                         ["distutils.command", "spork"])

        # Setting --command-packages to '' should cause the default to
        # be used even if a config file specified something else:
        sys.argv[1:] = ["--command-packages", "", "build"]
        d = self.create_distribution([TESTFN])
        self.assertEqual(d.get_command_packages(), ["distutils.command"])

Example 32

Project: kover
Source File: command_line.py
View license
    def from_tsv(self):
        parser = argparse.ArgumentParser(prog="kover dataset create from-tsv",
                                         description='Creates a Kover dataset from genomic data and optionally '
                                                     'phenotypic metadata')
        parser.add_argument('--genomic-data', help='A tab-separated file containing the k-mer matrix.',
                            required=True)
        parser.add_argument('--phenotype-name', help='An informative name that is assigned to the phenotypic metadata.')
        parser.add_argument('--phenotype-metadata', help='A file containing the phenotypic metadata.')
        parser.add_argument('--output', help='The Kover dataset to be created.', required=True)
        parser.add_argument('--compression', type=int, help='The gzip compression level (0 - 9). 0 means no compression'
                                                            '. The default value is 4.', default=4)
        parser.add_argument('-x', '--progress', help='Shows a progress bar for the execution.', action='store_true')
        parser.add_argument('-v', '--verbose', help='Sets the verbosity level.', default=False, action='store_true')

        # If no argument has been specified, default to help
        if len(argv) == 4:
            argv.append("--help")

        args = parser.parse_args(argv[4:])

        # Input validation logic
        if (args.phenotype_name is not None and args.phenotype_metadata is None) or (
                        args.phenotype_name is None and args.phenotype_metadata is not None):
            print "Error: The phenotype name and metadata file must be specified."
            exit()

        # Package imports
        from progressbar import Bar, Percentage, ProgressBar, Timer

        if args.verbose:
            logging.basicConfig(level=logging.DEBUG,
                                format="%(asctime)s.%(msecs)d %(levelname)s %(module)s - %(funcName)s: %(message)s")

        if args.progress:
            progress_vars = {"current_task": None, "pbar": None}

            def progress(task_name, p):
                if task_name != progress_vars["current_task"]:
                    if progress_vars["pbar"] is not None:
                        progress_vars["pbar"].finish()
                    progress_vars["current_task"] = task_name
                    progress_vars["pbar"] = ProgressBar(widgets=['%s: ' % task_name, Percentage(), Bar(), Timer()],
                                                        maxval=1.0)
                    progress_vars["pbar"].start()
                else:
                    progress_vars["pbar"].update(p)
        else:
            progress = None

        from kover.dataset.create import from_tsv
        from_tsv(tsv_path=args.genomic_data,
                 output_path=args.output,
                 phenotype_name=args.phenotype_name,
                 phenotype_metadata_path=args.phenotype_metadata,
                 gzip=args.compression,
                 progress_callback=progress)

        if args.progress:
            progress_vars["pbar"].finish()

Example 33

Project: downstream-farmer
Source File: test_unit.py
View license
    def test_parse_args_address(self):
        sys.argv.append('--address')
        sys.argv.append('testaddress')
        args = shell.parse_args()
        self.assertEqual(args.address, sys.argv[2])

Example 34

Project: kover
Source File: command_line.py
View license
    def from_contigs(self):
        parser = argparse.ArgumentParser(prog="kover dataset create from_contigs",
                                         description='Creates a Kover dataset from genomic data and optionally '
                                                     'phenotypic metadata')
        parser.add_argument('--genomic-data', help='A tab-separated file with one line per genome in the format '
                                                   'GENOME_ID{tab}PATH, where the path refers to a fasta file '
                                                   'containing the genome\'s contigs.',
                            required=True)
        parser.add_argument('--phenotype-name', help='An informative name that is assigned to the phenotypic metadata.')
        parser.add_argument('--phenotype-metadata', help='A file containing the phenotypic metadata.')
        parser.add_argument('--output', help='The Kover dataset to be created.', required=True)
        parser.add_argument('--kmer-size', help='The k-mer size (max is 128). The default is 31.', default=31)
        parser.add_argument('--singleton-kmers', help='Include k-mers that occur only once. Disabled by default.', default=False,
                            action='store_true')
        parser.add_argument('--n_cores', help='The number of cores used by DSK. The default value is 0 (all cores).',
                            default=0)
        parser.add_argument('--compression', type=int, help='The gzip compression level (0 - 9). 0 means no compression'
                                                            '. The default value is 4.', default=4)
        parser.add_argument('--temp-dir', help='Output directory for temporary files. The default is the system\'s temp dir.', default=gettempdir())
        parser.add_argument('-x', '--progress', help='Shows a progress bar for the execution.', action='store_true')
        parser.add_argument('-v', '--verbose', help='Sets the verbosity level.', default=False, action='store_true')

        # If no argument has been specified, default to help
        if len(argv) == 4:
            argv.append("--help")

        args = parser.parse_args(argv[4:])

        # Input validation logic
        if (args.phenotype_name is not None and args.phenotype_metadata is None) or (
                        args.phenotype_name is None and args.phenotype_metadata is not None):
            print "Error: The phenotype name and metadata file must be specified."
            exit()

        if args.verbose:
            logging.basicConfig(level=logging.DEBUG,
                                format="%(asctime)s.%(msecs)d %(levelname)s %(module)s - %(funcName)s: %(message)s")

        from kover.dataset.create import from_contigs

        if not args.singleton_kmers:
            filter_option = "singleton"
        else:
            filter_option = "nothing"

        from_contigs(contig_list_path=args.genomic_data,
                     output_path=args.output,
                     kmer_size=args.kmer_size,
                     filter_singleton=filter_option,
                     phenotype_name=args.phenotype_name,
                     phenotype_metadata_path=args.phenotype_metadata,
                     gzip=args.compression,
                     temp_dir=args.temp_dir,
                     nb_cores=args.n_cores,
                     verbose=args.verbose,
                     progress=args.progress)

Example 35

Project: imagrium
Source File: test_dist.py
View license
    def test_command_packages_unspecified(self):
        sys.argv.append("build")
        d = self.create_distribution()
        self.assertEqual(d.get_command_packages(), ["distutils.command"])

Example 36

Project: downstream-farmer
Source File: test_unit.py
View license
    def test_parse_args_token(self):
        sys.argv.append('--token')
        sys.argv.append('testtoken')
        args = shell.parse_args()
        self.assertEqual(args.token, sys.argv[2])

Example 37

Project: kover
Source File: command_line.py
View license
    def info(self):
        parser = argparse.ArgumentParser(prog="kover dataset info",
                                         description='Prints information about the content of a dataset')
        parser.add_argument('--dataset', help='The Kover dataset for which you require information.', required=True)
        parser.add_argument('--all', help='Prints all the available information.', action='store_true')
        parser.add_argument('--genome-type',
                            help='Prints the type of genomic data that was used to create the dataset.',
                            action='store_true')
        parser.add_argument('--genome-source', help='Prints the source (e.g.: path) from which the genomic data was'
                                                    ' acquired.', action='store_true')
        parser.add_argument('--genome-ids', help='Prints the identifiers of the genomes in the dataset.',
                            action='store_true')
        parser.add_argument('--genome-count', help='Prints the number of genomes in the dataset.', action='store_true')
        parser.add_argument('--kmers', help='Prints the sequence of each k-mer in the dataset (fasta).',
                            action='store_true')
        parser.add_argument('--kmer-len', help='Prints the length of the k-mers in the dataset.', action='store_true')
        parser.add_argument('--kmer-count', help='Prints the number of k-mers in the dataset.', action='store_true')
        parser.add_argument('--phenotype-name', help='Prints the identifier that was assigned to the phenotype.',
                            action='store_true')
        parser.add_argument('--phenotype-metadata',
                            help='Prints the path of the file from which the phenotypic metadata'
                                 ' was acquired.', action='store_true')
        parser.add_argument('--splits',
                            help='Prints the lists of splits of the dataset that are available for learning.',
                            action='store_true')
        parser.add_argument('--uuid', help='Prints the unique identifier of the dataset.', action='store_true')
        parser.add_argument('--compression', help='Print the data compression options of the dataset.',
                            action='store_true')

        # If no argument has been specified, default to help
        if len(argv) == 3:
            argv.append("--help")

        args = parser.parse_args(argv[3:])

        # Package imports
        from kover.dataset import KoverDataset

        dataset = args.dataset
        dataset = KoverDataset(dataset)
        if args.genome_type or args.all:
            print "Genome type:", dataset.genome_source_type
            print
        if args.genome_source or args.all:
            print "Genome source:", dataset.genome_source
            print
        if args.genome_ids or args.all:
            print "Genome IDs:"
            for id in dataset.genome_identifiers:
                print id
            print
        if args.genome_count:
            print "Genome count:", dataset.genome_count
            print
        if args.kmers or args.all:
            print "Kmer sequences (fasta):"
            for i, k in enumerate(dataset.kmer_sequences):
                print ">k%d" % (i + 1)
                print k
            print
        if args.kmer_len or args.all:
            print "K-mer length:", dataset.kmer_length
            print
        if args.kmer_count or args.all:
            print "K-mer count:", dataset.kmer_count
            print
        if args.phenotype_name or args.all:
            print "Phenotype name:", dataset.phenotype.name
            print
        if args.phenotype_metadata or args.all:
            if dataset.phenotype.name != "NA":
                print "Phenotype metadata source:", dataset.phenotype.metadata_source
            else:
                print "No phenotype metadata."
            print
        if args.compression or args.all:
            print "Compression:", dataset.compression
            print
        if args.splits or args.all:
            splits = dataset.splits
            if len(splits) > 0:
                print "The following splits are available for learning:"
                for split in splits:
                    print split
            else:
                print "There are no splits available for learning."

Example 38

Project: kover
Source File: command_line.py
View license
    def split(self):
        parser = argparse.ArgumentParser(prog="kover dataset split",
                                         description='Splits a kover dataset file into a training set, a testing set '
                                                     'and optionally cross-validation folds')
        parser.add_argument('--dataset', help='The Kover dataset to be split.', required=True)
        parser.add_argument('--id', help='A unique identifier that will be assigned to the split.', required=True)
        parser.add_argument('--train-size', type=float, help='The proportion of the data that will be reserved for '
                                                             'training the learning algorithm (default is 0.5). Alternatively, you can specify which '
                                                             'genomes to use for training and testing by using --train-ids and --test-ids.',
                            default=0.5)
        parser.add_argument('--train-ids', type=str, nargs='+', help='The identifiers of the genomes used to train the '
                                                                     'learning algorithm. If you provide a value for this argument, you must also provide a '
                                                                     'value for --test-ids.')
        parser.add_argument('--test-ids', type=str, nargs='+', help='The identifiers of the genomes used to evaluate '
                                                                    'the accuracy of the model generated. If you provide a value for this argument, you must '
                                                                    'also provide a value for --train-ids.')
        parser.add_argument('--folds', type=int,
                            help='The number of k-fold cross-validation folds to create (default is 0 for none, '
                                 'the minimum value is 2). Folds are required for using k-fold cross-validation '
                                 'in \'kover learn\'.', default=0)
        parser.add_argument('--random-seed', type=int, help='A random seed used for randomly splitting the data. A '
                                                            'specific seed will always lead to the same split. If not provided, it is set randomly.')
        parser.add_argument('-v', '--verbose', help='Sets the verbosity level.', default=False, action='store_true')
        parser.add_argument('-x', '--progress', help='Shows a progress bar for the execution.', action='store_true')

        # If no argument has been specified, default to help
        if len(argv) == 3:
            argv.append("--help")

        args = parser.parse_args(argv[3:])

        # Validate the number of cross-validation folds
        if args.folds == 1:
            print "Error: The number of cross-validation folds must be 0 or >= 2."
            exit()

        # Validate that training and testing genome ids are both specified if one of them is specified
        if (args.train_ids is not None and args.test_ids is None) or \
                (args.test_ids is not None and args.train_ids is None):
            print "Error: Training and testing genome identifiers must be specified simultaneously."
            exit()

        # Package imports
        from kover.dataset.split import split_with_ids, split_with_proportion
        from progressbar import Bar, Percentage, ProgressBar, Timer
        from random import randint

        if args.verbose:
            logging.basicConfig(level=logging.DEBUG,
                                format="%(asctime)s.%(msecs)d %(levelname)s %(module)s - %(funcName)s: %(message)s")

        if args.random_seed is None:
            args.random_seed = randint(0, 4294967295)

        if args.progress:
            progress_vars = {"current_task": None, "pbar": None}

            def progress(task_name, p):
                if task_name != progress_vars["current_task"]:
                    if progress_vars["pbar"] is not None:
                        progress_vars["pbar"].finish()
                    progress_vars["current_task"] = task_name
                    progress_vars["pbar"] = ProgressBar(widgets=['%s: ' % task_name, Percentage(), Bar(), Timer()],
                                                        maxval=1.0)
                    progress_vars["pbar"].start()
                else:
                    progress_vars["pbar"].update(p)
        else:
            progress = None

        if args.train_ids is not None and args.test_ids is not None:
            split_with_ids(input=args.dataset,
                           split_name=args.id,
                           train_ids=args.train_ids,
                           test_ids=args.test_ids,
                           random_seed=args.random_seed,
                           n_folds=args.folds,
                           progress_callback=progress)
        else:
            split_with_proportion(input=args.dataset,
                                  split_name=args.id,
                                  train_prop=args.train_size,
                                  random_seed=args.random_seed,
                                  n_folds=args.folds,
                                  progress_callback=progress)

        if args.progress:
            progress_vars["pbar"].finish()

Example 39

Project: downstream-farmer
Source File: test_unit.py
View license
    def test_parse_args_url(self):
        sys.argv.append('testurl')
        args = shell.parse_args()
        self.assertEqual(args.node_url, sys.argv[1])

Example 40

Project: kover
Source File: command_line.py
View license
    def __init__(self):
        self.available_commands = ['dataset', 'learn']

        parser = argparse.ArgumentParser(description=KOVER_DESCRIPTION)
        parser.add_argument('--cite', action='store_true',
                            help='Show the references to cite if you use Kover in your work')
        parser.add_argument('--license', action='store_true',
                            help='Show the license for your release of Kover')
        parser.add_argument('--version', action='store_true',
                            help='Show the version of your release of Kover')
        parser.add_argument('command', help='Available commands', choices=self.available_commands)

        # If no argument has been specified, default to help
        if len(argv) == 1:
            argv.append("--help")

        # Detect if an option or a command was specified
        if "--" == argv[1][:2]:
            args = parser.parse_args([argv[1], "learn"])

            if args.license:
                print \
"""
Kover: Learn interpretable computational phenotyping models from k-merized genomic data
Copyright (C) 2015  Alexandre Drouin

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
            elif args.version:
                print "cli-%s" % VERSION
                print "core-%s" % get_distribution('kover').version

            elif args.cite:
                print \
"""If you used Kover in your work, please cite our paper:

Drouin, A., Giguère, S., Déraspe, M., Marchand, M., Tyers, M., Loo, V. G., Bourgault, A. M., Laviolette, F. & Corbeil, J. (2016). Predictive computational phenotyping and biomarker discovery using reference-free genome comparisons. BMC Genomics, 17(1), 754.


Bibtex:

@article{Drouin2016,
author="Drouin, Alexandre
and Gigu{\\`e}re, S{\\'e}bastien
and D{\\'e}raspe, Maxime
and Marchand, Mario
and Tyers, Michael
and Loo, Vivian G.
and Bourgault, Anne-Marie
and Laviolette, Fran{\\c{c}}ois
and Corbeil, Jacques",
title="Predictive computational phenotyping and biomarker discovery using reference-free genome comparisons",
journal="BMC Genomics",
year="2016",
volume="17",
number="1",
pages="754",
issn="1471-2164",
doi="10.1186/s12864-016-2889-6",
url="http://dx.doi.org/10.1186/s12864-016-2889-6"
}
"""
        else:
            args = parser.parse_args(argv[1:2])
            if not hasattr(self, args.command):
                print 'kover: \'%s\' is not a kover command. See \'%s --help\'.' % (args.command, argv[0])

                parser.print_help()
                exit(1)
            getattr(self, args.command)()

Example 41

Project: imagrium
Source File: test_dist.py
View license
    def test_command_packages_configfile(self):
        sys.argv.append("build")
        self.addCleanup(os.unlink, TESTFN)
        f = open(TESTFN, "w")
        try:
            print >> f, "[global]"
            print >> f, "command_packages = foo.bar, splat"
        finally:
            f.close()

        d = self.create_distribution([TESTFN])
        self.assertEqual(d.get_command_packages(),
                         ["distutils.command", "foo.bar", "splat"])

        # ensure command line overrides config:
        sys.argv[1:] = ["--command-packages", "spork", "build"]
        d = self.create_distribution([TESTFN])
        self.assertEqual(d.get_command_packages(),
                         ["distutils.command", "spork"])

        # Setting --command-packages to '' should cause the default to
        # be used even if a config file specified something else:
        sys.argv[1:] = ["--command-packages", "", "build"]
        d = self.create_distribution([TESTFN])
        self.assertEqual(d.get_command_packages(), ["distutils.command"])

Example 42

Project: TrustRouter
Source File: test_dist.py
View license
    def test_command_packages_unspecified(self):
        sys.argv.append("build")
        d = self.create_distribution()
        self.assertEqual(d.get_command_packages(), ["distutils.command"])

Example 43

Project: kover
Source File: command_line.py
View license
    def learn(self):
        parser = argparse.ArgumentParser(prog='kover learn', description='Learn a model from data')
        parser.add_argument('--dataset', help='The Kover dataset from which to learn.', required=True)
        parser.add_argument('--split', help='The identifier of the split of the dataset to use for learning.',
                            required=True)
        parser.add_argument('--model-type', choices=['conjunction', 'disjunction'], nargs='+',
                            help='Hyperparameter: The type of model to learn, conjunction (logical-AND) or disjunction '
                                 '(logical-OR). You can specify multiple space separated values. Refer to the documentation '
                                 'for more information.',
                            default=['conjunction', 'disjunction'])
        parser.add_argument('--p', type=float, nargs='+',
                            help='Hyperparameter: The value of the trade-off parameter in the rule scoring criterion. '
                                 'You can specify multiple space separated values. Refer to the documentation for '
                                 'more information.',
                            default=[0.1, 0.316, 0.562, 1.0, 1.778, 3.162, 10.0, 999999.0])
        parser.add_argument('--max-rules', type=int, help='The maximum number of rules that can be included in the '
                                                          'model.', default=10)
        parser.add_argument('--max-equiv-rules', type=int, help='The maximum number of equivalent rules to report for '
                                                                'each rule in the model. This only affects model interpretation. Use the default unless you'
                                                                ' expect that the rules in the model will be equivalent to more than 10000 other rules.',
                            default=10000)
        parser.add_argument('--hp-choice', choices=['bound', 'cv', 'none'],
                            help='The strategy used to select the best values for hyperparameters. The default is '
                                 'k-fold cross-validation, where k is the number of folds defined in the split. Other '
                                 'strategies, such as bound selection are available (refer to the documentation). Using none '
                                 'selects the first value specified for each hyperparameter.', default='cv')
        parser.add_argument('--bound-max-genome-size', type=int, help='Specify this only if --hp-choice is bound. The '
                                                                      'maximum size, in base pairs, of any genome in the dataset. If you are unsure about this '
                                                                      'value, you should use an overestimation. This will only affect the tightness of the bound '
                                                                      'on the error rate. By default number of k-mers in the dataset is used.')
        parser.add_argument('--random-seed', type=int, help='The random seed used for any random operation. '
                                                            'Set this if only if you require that the same random choices are made between repeats.')
        parser.add_argument('--n-cpu', type=int, help='The number of CPUs used to select the hyperparameter values. '
                                                      'Make sure your computer has enough RAM to handle multiple simultaneous trainings of the '
                                                      'algorithm and that your storage device will not be a bottleneck (simultaneous reading).',
                            default=1)
        parser.add_argument('--output-dir',
                            help='The directory in which to store Kover\'s output. It will be created if '
                                 'it does not exist.', default='.')
        parser.add_argument('-x', '--progress', help='Shows a progress bar for the execution.', action='store_true')
        parser.add_argument('-v', '--verbose', help='Sets the verbosity level.', default=False, action='store_true')

        # If no argument has been specified, default to help
        if len(argv) == 2:
            argv.append("--help")

        args = parser.parse_args(argv[2:])

        # Package imports
        from datetime import timedelta
        from json import dump as json_dump
        from kover.dataset import KoverDataset
        from kover.learning.experiment import learn
        from os import mkdir
        from os.path import abspath, exists, join
        from progressbar import Bar, Percentage, ProgressBar, Timer
        from time import time

        # Input validation
        dataset = KoverDataset(args.dataset)
        dataset_kmer_count = dataset.kmer_count
        # - Check that the split exists
        try:
            dataset.get_split(args.split)
        except:
            print "Error: The split (%s) does not exist in the dataset. Use 'kover dataset split' to create it." % args.split
            exit()
        # - Must have at least 2 folds to perform cross-validation
        if args.hp_choice == "cv" and len(dataset.get_split(args.split).folds) < 2:
            print "Error: The split must contain at least 2 folds in order to perform cross-validation. " \
                  "Use 'kover dataset split' to create folds."
            exit()
        del dataset

        if args.verbose:
            logging.basicConfig(level=logging.DEBUG,
                                format="%(asctime)s.%(msecs)d %(levelname)s %(module)s - %(funcName)s [%(process)d]: %(message)s")

        if args.progress:
            progress_vars = {"current_task": None, "pbar": None}

            def progress(task_name, p):
                if task_name != progress_vars["current_task"]:
                    if progress_vars["pbar"] is not None:
                        progress_vars["pbar"].finish()
                    progress_vars["current_task"] = task_name
                    progress_vars["pbar"] = ProgressBar(widgets=['%s: ' % task_name, Percentage(), Bar(), Timer()],
                                                        maxval=1.0)
                    progress_vars["pbar"].start()
                else:
                    progress_vars["pbar"].update(p)
        else:
            progress = None

        start_time = time()
        best_hp, best_hp_score, \
        train_metrics, test_metrics, \
        model, rule_importances, \
        equivalent_rules, \
        classifications = learn(dataset_file=args.dataset,
                                split_name=args.split,
                                model_type=args.model_type,
                                p=args.p,
                                max_rules=args.max_rules,
                                max_equiv_rules=args.max_equiv_rules,
                                bound_delta=0.05,  # We use a fixed 5% delta to simplify the user experience
                                bound_max_genome_size=args.bound_max_genome_size
                                if args.bound_max_genome_size is not None
                                else dataset_kmer_count,
                                parameter_selection=args.hp_choice,
                                n_cpu=args.n_cpu,
                                random_seed=args.random_seed,
                                progress_callback=progress)
        running_time = timedelta(seconds=time() - start_time)

        if args.progress:
            progress_vars["pbar"].finish()

        # Write a report (user friendly)
        metric_aliases = [("risk", "Error Rate"), ("sensitivity", "Sensitivity"), ("specificity", "Specificity"),
                          ("precision", "Precision"), ("recall", "Recall"), ("f1_score", "F1 Score"),
                          ("tp", "True Positives"), ("tn", "True Negatives"),
                          ("fp", "False Positives"), ("fn", "False Negatives")]
        dataset = KoverDataset(args.dataset)
        split = dataset.get_split(args.split)
        report = ""
        report += "Kover Learning Report\n" + "=" * 21 + "\n"
        report += "\n"
        report += "Running time: %s\n" % running_time
        report += "\n"
        report += "Configuration:\n" + "-" * 14 + "\n"
        for key in sorted(args.__dict__.keys()):
            report += "%s: %s\n" % (str(key), str(args.__dict__[key]))
        report += "\n"
        report += "Data summary:\n" + "-" * 13 + "\n"
        report += "Dataset file: %s\n" % abspath(args.dataset)
        report += "Dataset UUID: %s\n" % dataset.uuid
        report += "Phenotype: %s\n" % dataset.phenotype.name.title()
        report += "Genomic data type: %s\n" % dataset.genome_source_type
        report += "Split: %s\n" % args.split
        report += "Number of genomes used for training: %d (Group 1: %d, Group 0: %d)\n" % (
            len(split.train_genome_idx),
            (dataset.phenotype.metadata[split.train_genome_idx] == 1).sum(),
            (dataset.phenotype.metadata[split.train_genome_idx] == 0).sum())
        report += "Number of genomes used for testing: %d (Group 1: %d, Group 0: %d)\n" % (
            len(split.test_genome_idx),
            (dataset.phenotype.metadata[split.test_genome_idx] == 1).sum() if len(split.test_genome_idx) > 0 else 0,
            (dataset.phenotype.metadata[split.test_genome_idx] == 0).sum() if len(split.test_genome_idx) > 0 else 0)
        report += "Number of k-mers: %d\n" % dataset.kmer_count
        if dataset.genome_source_type == "contigs":
            report += "K-mer size : %s\n" % dataset.kmer_length
            report += "K-mer filtering : %s\n" % dataset.kmer_filter
        report += "\n"
        report += "Hyperparameter Values:\n" + "-" * 22 + "\n"
        if args.hp_choice == "cv":
            report += "Selection strategy: %d-fold cross-validation (score = %.5f)\n" % (
                len(split.folds), best_hp_score)
        elif args.hp_choice == "bound":
            report += "Selection strategy: bound selection (score = %.5f)\n" % best_hp_score
        else:
            report += "Selection strategy: No selection\n"
        report += "Model type: %s\n" % best_hp["model_type"]
        report += "p: %f\n" % best_hp["p"]
        report += "Maximum number of rules: %d\n" % best_hp["max_rules"]
        report += "\n"
        # Write the training set metrics
        report += "Metrics (training data)\n" + "-" * 23 + "\n"
        for key, alias in metric_aliases:
            report += "%s: %s\n" % (str(alias), str(round(train_metrics[key][0], 5)))
        report += "\n"
        # Write the testing set metrics
        if test_metrics is not None:
            report += "Metrics (testing data)\n" + "-" * 22 + "\n"
            for key, alias in metric_aliases:
                report += "%s: %s\n" % (str(alias), str(round(test_metrics[key][0], 5)))
            report += "\n"
        # Write the model
        report += "Model (%s - %d rules):\n" % (model.type.title(), len(model)) + "-" * (
            18 + len(model.type) + len(str(len(model)))) + "\n"
        report += ("\n%s\n" % ("AND" if model.type == "conjunction" else "OR")).join(
            ["%s [Importance: %.2f, %d equivalent rules]" % (str(rule), importance, len(equivalent_rules[i])) for
             i, (rule, importance) in enumerate(zip(model, rule_importances))])
        report += "\n"

        # Show the report
        print report

        # Create the output directory
        if not exists(args.output_dir):
            mkdir(args.output_dir)

        # Write report
        with open(join(args.output_dir, "report.txt"), "w") as f:
            f.write(report)

        # Save detailed results to json
        results = {"data": {"uuid": dataset.uuid,
                            "path": dataset.path,
                            "split": args.split},
                   "cv": {"best_hp": {"values": best_hp,
                                      "score": best_hp_score},
                          "candidate_hp": {"model_type": args.model_type,
                                           "p": args.p,
                                           "max_rules": args.max_rules},
                          "strategy": args.hp_choice},
                   "metrics": {"train": train_metrics,
                               "test": test_metrics},
                   "model": {"n_rules": len(model),
                             "rules": [str(r) for r in model],
                             "rule_importances": rule_importances.tolist(),
                             "type": best_hp["model_type"]},
                   "classifications": classifications,
                   "running_time": running_time.seconds}
        with open(join(args.output_dir, 'results.json'), 'w') as f:
            json_dump(results, f)

        # Save command line arguments to json
        config = dict((k, v) for k, v in args.__dict__.iteritems())
        config["dataset"] = abspath(config['dataset'])
        with open(join(args.output_dir, 'config.json'), 'w') as f:
            json_dump(config, f)

        # Save model (also equivalent rules) [Fasta]
        with open(join(args.output_dir, 'model.fasta'), "w") as f:
            for i, (rule, importance) in enumerate(zip(model, rule_importances)):
                f.write(">rule-%d %s, importance: %.2f\n%s\n\n" % (i + 1, rule.type, importance, rule.kmer_sequence))
                with open(join(args.output_dir, "model_rule_%i_equiv.fasta" % (i + 1)), "w") as f_equiv:
                    f_equiv.write("\n\n".join(
                        [">rule-%d-equiv-%d,%s\n%s" % (i + 1, j + 1, rule.type, rule.kmer_sequence)
                         for j, rule in enumerate(equivalent_rules[i])]))

Example 44

Project: TrustRouter
Source File: test_dist.py
View license
    def test_command_packages_configfile(self):
        sys.argv.append("build")
        self.addCleanup(os.unlink, TESTFN)
        f = open(TESTFN, "w")
        try:
            print("[global]", file=f)
            print("command_packages = foo.bar, splat", file=f)
        finally:
            f.close()

        d = self.create_distribution([TESTFN])
        self.assertEqual(d.get_command_packages(),
                         ["distutils.command", "foo.bar", "splat"])

        # ensure command line overrides config:
        sys.argv[1:] = ["--command-packages", "spork", "build"]
        d = self.create_distribution([TESTFN])
        self.assertEqual(d.get_command_packages(),
                         ["distutils.command", "spork"])

        # Setting --command-packages to '' should cause the default to
        # be used even if a config file specified something else:
        sys.argv[1:] = ["--command-packages", "", "build"]
        d = self.create_distribution([TESTFN])
        self.assertEqual(d.get_command_packages(), ["distutils.command"])

Example 45

Project: Ezhil-Lang
Source File: ezhil.py
View license
def add_stdin():
    sys.argv.append('-stdin')

Example 46

Project: datafari
Source File: test_dist.py
View license
    def test_debug_mode(self):
        with open(TESTFN, "w") as f:
            f.write("[global]\n")
            f.write("command_packages = foo.bar, splat")
        self.addCleanup(unlink, TESTFN)

        files = [TESTFN]
        sys.argv.append("build")

        with captured_stdout() as stdout:
            self.create_distribution(files)
        stdout.seek(0)
        self.assertEqual(stdout.read(), '')
        distutils.dist.DEBUG = True
        try:
            with captured_stdout() as stdout:
                self.create_distribution(files)
            stdout.seek(0)
            self.assertEqual(stdout.read(), '')
        finally:
            distutils.dist.DEBUG = False

Example 47

Project: pymo
Source File: test_dist.py
View license
    def test_command_packages_unspecified(self):
        sys.argv.append("build")
        d = self.create_distribution()
        self.assertEqual(d.get_command_packages(), ["distutils.command"])

Example 48

Project: pydtls
Source File: setup.py
View license
def make_dists():
    prebuilt_platform_root = path.join("dtls", "prebuilt")
    for platform in listdir(prebuilt_platform_root):
        config = {"MANIFEST_DIR": path.join(prebuilt_platform_root, platform)}
        execfile(path.join(prebuilt_platform_root, platform, "manifest.pycfg"),
                 config)
        files = map(lambda x: "dtls/prebuilt/" + platform + "/" + x,
                    config["FILES"])
        argv.append("--formats=" + config["FORMATS"])
        invoke_setup([('dtls', files)])
        del argv[-1]
        for dist_format in config["FORMATS"].split(','):
            source_name = path.join(DIST_DIR,
                                    NAME + "-" + VERSION +
                                    FORMAT_TO_SUFFIX[dist_format])
            target_name = path.join(DIST_DIR,
                                    NAME + "-" + VERSION +
                                    ".sdist_with_openssl." +
                                    config["ARCHITECTURE"] +
                                    FORMAT_TO_SUFFIX[dist_format])
            try:
                remove(target_name)
            except OSError:
                pass
            rename(source_name, target_name)

Example 49

Project: RIDE
Source File: time_tests.py
View license
def collect_execution_times(test_modules):
    sys.argv.append('--match=^test')
    sys.argv.append('-q')
    for tmodule in test_modules:
        yield(tmodule, _test_module_execution_time(tmodule))

Example 50

Project: pyina
Source File: epydocify.py
View license
def epydocify():
    dirname = os.path.dirname(__file__)
    config = os.path.join(dirname, 'epydoc.cfg')
    sys.argv.append('--config=' + config)
    epydoc.cli.cli()