Python shlex.quote() Examples

The following are 30 code examples of shlex.quote(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module shlex , or try the search function .
Example #1
Source File: compat.py    From streamlink with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def shlex_quote(s):
    """Return a shell-escaped version of the string *s*.

    Backported from Python 3.3 standard library module shlex.
    """

    if is_py3:  # use the latest version instead of backporting if it's available
        return quote(s)

    if not s:
        return "''"
    if _find_unsafe(s) is None:
        return s

    # use single quotes, and put single quotes into double quotes
    # the string $'b is then quoted as '$'"'"'b'
    return "'" + s.replace("'", "'\"'\"'") + "'" 
Example #2
Source File: train.py    From monoses with GNU General Public License v3.0 6 votes vote down vote up
def train_lm(args):
    root = args.working + '/step2'
    os.mkdir(root)
    for part in ('src', 'trg'):
        bash(quote(MOSES + '/bin/lmplz') +
             ' -T ' + quote(args.tmp + '/lm') +
             ' -o ' + str(args.lm_order) +
             ' --prune ' + ' '.join(map(str, args.lm_prune)) +
             ' < ' + quote(args.working + '/step1/train.true.' + part) +
             ' > ' + quote(args.tmp + '/model.arpa'))
        bash(quote(MOSES + '/bin/build_binary') +
             ' ' + quote(args.tmp + '/model.arpa') +
             ' ' + quote(root + '/' + part + '.blm'))
        os.remove(args.tmp + '/model.arpa')


# Step 3: Train embeddings 
Example #3
Source File: train.py    From monoses with GNU General Public License v3.0 6 votes vote down vote up
def induce_phrase_table(args):
    root = args.working + '/step5'
    os.mkdir(root)
    bash('export OMP_NUM_THREADS=' + str(args.threads) + ';'
         ' python3 '  + quote(TRAINING + '/induce-phrase-table.py') +
         ' --src ' + quote(args.working + '/step4/emb.src') +
         ' --trg ' + quote(args.working + '/step4/emb.trg') +
         ' --src2trg ' + quote(args.tmp + '/src2trg.phrase-table') +
         ' --trg2src ' + quote(args.tmp + '/trg2src.phrase-table'))
    for part in 'src2trg', 'trg2src':
        bash('export LC_ALL=C;' +
             ' sort -S 10G --batch-size 253 --compress-program gzip' +
             ' --parallel ' + str(args.threads) + ' -T ' + quote(args.tmp) +
             ' ' + quote(args.tmp + '/' + part + '.phrase-table') +
             ' | gzip > ' + quote(root + '/' + part + '.phrase-table.gz'))
        os.remove(args.tmp + '/' + part + '.phrase-table')


# Step 6: Build initial model 
Example #4
Source File: translate.py    From monoses with GNU General Public License v3.0 6 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='Translate text using a trained model')
    parser.add_argument('model', metavar='PATH', help='Working directory of the trained model')
    parser.add_argument('-r', '--reverse', action='store_true', help='Use the reverse model (trg->src)')
    parser.add_argument('--src', metavar='STR', required=True, help='Input language code')
    parser.add_argument('--trg', metavar='STR', required=True, help='Output language code')
    parser.add_argument('--threads', metavar='N', type=int, default=20, help='Number of threads (defaults to 20)')
    parser.add_argument('--tok', action='store_true', help='Do not detokenize')
    args = parser.parse_args()

    direction = 'trg2src' if args.reverse else 'src2trg'
    detok = '' if args.tok else ' | ' + quote(MOSES + '/scripts/tokenizer/detokenizer.perl') + ' -q -l ' + quote(args.trg)
    bash(quote(MOSES + '/scripts/tokenizer/tokenizer.perl') +
               ' -l ' + quote(args.src) + ' -threads ' + str(args.threads) +
               ' 2> /dev/null' +
         ' | ' + quote(MOSES + '/scripts/recaser/truecase.perl') +
               ' --model ' + quote(args.model + '/step1/truecase-model.' + direction[:3]) +
         ' | ' + quote(MOSES + '/bin/moses2') +
               ' -f ' + quote(args.model + '/' + direction + '.moses.ini') +
               ' --threads ' + str(args.threads) +
               ' 2> /dev/null' +
         ' | ' + quote(MOSES + '/scripts/recaser/detruecase.perl') +
         detok
         ) 
Example #5
Source File: subprocess.py    From briefcase with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run(self, args, **kwargs):
        """A wrapper for subprocess.run()

        If verbosity >= 2, the executed command will be printed to the console.

        The behavior of this method is identical to subprocess.run(),
        except for the `env` argument. If provided, the current system
        environment will be copied, and the contents of env overwritten
        into that environment.
        """
        # Invoke subprocess.run().
        # Pass through all arguments as-is.
        # All exceptions are propegated back to the caller.
        if self.command.verbosity >= 2:
            print(">>> {cmdline}".format(
                cmdline=' '.join(shlex.quote(arg) for arg in args)
            ))

        return self._subprocess.run(
            [
                str(arg) for arg in args
            ],
            **self.final_kwargs(**kwargs)
        ) 
Example #6
Source File: subprocess.py    From briefcase with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_output(self, args, **kwargs):
        """A wrapper for subprocess.check_output()

        If verbosity >= 2, the executed command will be printed to the console.

        The behavior of this method is identical to subprocess.check_output(),
        except for the `env` argument. If provided, the current system
        environment will be copied, and the contents of env overwritten
        into that environment.
        """
        # Invoke subprocess.check_output
        if self.command.verbosity >= 2:
            print(">>> {cmdline}".format(
                cmdline=' '.join(shlex.quote(arg) for arg in args)
            ))

        return self._subprocess.check_output(
            [
                str(arg) for arg in args
            ],
            **self.final_kwargs(**kwargs)
        ) 
Example #7
Source File: subprocess.py    From briefcase with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def Popen(self, args, **kwargs):
        """A wrapper for subprocess.Popen()

        If verbosity >= 2, the executed command will be printed to the console.

        The behavior of this method is identical to subprocess.Popen(),
        except for the `env` argument. If provided, the current system
        environment will be copied, and the contents of env overwritten
        into that environment.
        """
        # Invoke subprocess.check_output
        if self.command.verbosity >= 2:
            print(">>> {cmdline}".format(
                cmdline=' '.join(shlex.quote(arg) for arg in args)
            ))

        return self._subprocess.Popen(
            [
                str(arg) for arg in args
            ],
            **self.final_kwargs(**kwargs)
        ) 
Example #8
Source File: common.py    From adversarial-policies with MIT License 6 votes vote down vote up
def _rsync_func(local_dir, remote_uri):
    """rsync data from worker to a remote location (by default the driver)."""
    # SOMEDAY: This function blocks until syncing completes, which is unfortunate.
    # If we instead specified a shell command, ray.tune._LogSyncer would run it asynchronously.
    # But we need to do a two-stage command, creating the directories first, because rsync will
    # balk if destination directory does not exist; so no easy way to do that.
    remote_host, ssh_key, *remainder = remote_uri.split(":")
    remote_dir = ":".join(remainder)  # remote directory may contain :
    remote_dir = shlex.quote(remote_dir)  # make safe for SSH/rsync call

    ssh_command = ["ssh", "-o", "StrictHostKeyChecking=no", "-i", ssh_key]
    ssh_mkdir = ssh_command + [remote_host, "mkdir", "-p", remote_dir]
    subprocess.run(ssh_mkdir, check=True)

    rsync = [
        "rsync",
        "-rlptv",
        "-e",
        " ".join(ssh_command),
        f"{local_dir}/",
        f"{remote_host}:{remote_dir}",
    ]
    subprocess.run(rsync) 
Example #9
Source File: dispatcher.py    From resolwe with Apache License 2.0 6 votes vote down vote up
def _include_environment_variables(self, program, executor_vars):
        """Define environment variables."""
        env_vars = {
            "RESOLWE_HOST_URL": self.settings_actual.get(
                "RESOLWE_HOST_URL", "localhost"
            ),
        }

        set_env = self.settings_actual.get("FLOW_EXECUTOR", {}).get("SET_ENV", {})
        env_vars.update(executor_vars)
        env_vars.update(set_env)

        export_commands = [
            "export {}={}".format(key, shlex.quote(value))
            for key, value in env_vars.items()
        ]
        return os.linesep.join(export_commands) + os.linesep + program 
Example #10
Source File: archive.py    From bob with GNU General Public License v3.0 6 votes vote down vote up
def __uploadJenkins(self, step, keyFile, contentFile, suffix):
        # only upload if requested
        if not self.canUploadJenkins():
            return ""

        # upload with curl if file does not exist yet on server
        insecure = "" if self.__sslVerify else "-k"
        return "\n" + textwrap.dedent("""\
            # upload artifact
            cd $WORKSPACE
            BOB_UPLOAD_BID="$(hexdump -ve '/1 "%02x"' {KEYFILE}){GEN}"
            BOB_UPLOAD_URL={URL}"/${{BOB_UPLOAD_BID:0:2}}/${{BOB_UPLOAD_BID:2:2}}/${{BOB_UPLOAD_BID:4}}{SUFFIX}"
            if ! curl --output /dev/null --silent --head --fail {INSECURE} "$BOB_UPLOAD_URL" ; then
                BOB_UPLOAD_RSP=$(curl -sSgf {INSECURE} -w '%{{http_code}}' -H 'If-None-Match: *' -T {CONTENTFILE} "$BOB_UPLOAD_URL" || true)
                if [[ $BOB_UPLOAD_RSP != 2?? && $BOB_UPLOAD_RSP != 412 ]]; then
                    echo "Upload failed with code $BOB_UPLOAD_RSP"{FAIL}
                fi
            fi""".format(URL=quote(self.__url.geturl()), KEYFILE=quote(keyFile),
                         CONTENTFILE=quote(contentFile),
                         FAIL="" if self._ignoreErrors() else "; exit 1",
                         GEN=ARCHIVE_GENERATION, SUFFIX=suffix,
                         INSECURE=insecure)) 
Example #11
Source File: archive.py    From bob with GNU General Public License v3.0 6 votes vote down vote up
def __uploadJenkins(self, step, buildIdFile, tgzFile, suffix):
        # only upload if requested
        if not self.canUploadJenkins():
            return ""

        cmd = self.__uploadCmd
        if self._ignoreErrors():
            # wrap in subshell
            cmd = "( " + cmd + " ) || echo Upload failed: $?"

        return "\n" + textwrap.dedent("""\
            # upload artifact
            cd $WORKSPACE
            BOB_UPLOAD_BID="$(hexdump -ve '/1 "%02x"' {BUILDID}){GEN}"
            BOB_LOCAL_ARTIFACT={RESULT}
            BOB_REMOTE_ARTIFACT="${{BOB_UPLOAD_BID:0:2}}/${{BOB_UPLOAD_BID:2:2}}/${{BOB_UPLOAD_BID:4}}{SUFFIX}"
            """.format(BUILDID=quote(buildIdFile), RESULT=quote(tgzFile),
                       GEN=ARCHIVE_GENERATION, SUFFIX=suffix)) + cmd 
Example #12
Source File: archive.py    From bob with GNU General Public License v3.0 6 votes vote down vote up
def __uploadJenkins(self, step, keyFile, contentFile, suffix):
        if not self.canUploadJenkins():
            return ""

        args = []
        if self.__key: args.append("--key=" + self.__key)
        if self.__sasToken: args.append("--sas-token=" + self.__sasToken)

        return "\n" + textwrap.dedent("""\
            # upload artifact
            cd $WORKSPACE
            bob _upload azure {ARGS} {ACCOUNT} {CONTAINER} {KEYFILE} {SUFFIX} {CONTENTFILE}{FIXUP}
            """.format(ARGS=" ".join(map(quote, args)), ACCOUNT=quote(self.__account),
                       CONTAINER=quote(self.__container), KEYFILE=quote(keyFile),
                       CONTENTFILE=quote(contentFile),
                       FIXUP=" || echo Upload failed: $?" if self._ignoreErrors() else "",
                       SUFFIX=suffix)) 
Example #13
Source File: data_handler.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def _get_memory_tool_options(testcase):
  """Return memory tool options as a string to pass on command line."""
  env = testcase.get_metadata('env')
  if not env:
    return []

  result = []
  for options_name, options_value in sorted(six.iteritems(env)):
    # Strip symbolize flag, use default symbolize=1.
    options_value.pop('symbolize', None)
    if not options_value:
      continue

    options_string = environment.join_memory_tool_options(options_value)
    result.append('{options_name}="{options_string}"'.format(
        options_name=options_name, options_string=quote(options_string)))

  return result 
Example #14
Source File: wxbot.py    From DevilYuan with MIT License 6 votes vote down vote up
def show_image(file_path):
    """
    跨平台显示图片文件
    :param file_path: 图片文件路径
    """
    if sys.version_info >= (3, 3):
        from shlex import quote
    else:
        from pipes import quote

    if sys.platform == "darwin":
        command = "open -a /Applications/Preview.app %s&" % quote(file_path)
        os.system(command)
    else:
        img = PIL.Image.open(file_path)
        img.show() 
Example #15
Source File: lithium_helpers.py    From funfuzz with Mozilla Public License 2.0 5 votes vote down vote up
def run_lithium(lithArgs, logPrefix, targetTime):  # pylint: disable=invalid-name,missing-param-doc,missing-return-doc
    # pylint: disable=missing-return-type-doc,missing-type-doc
    """Run Lithium as a subprocess: reduce to the smallest file that has at least the same unhappiness level.

    Returns a tuple of (lithlogfn, LITH_*, details).
    """
    deletableLithTemp = None  # pylint: disable=invalid-name
    if targetTime:
        # loop is being used by bot
        deletableLithTemp = tempfile.mkdtemp(prefix="fuzzbot-lithium")  # pylint: disable=invalid-name
        lithArgs = [f"--maxruntime={targetTime}", f"--tempdir={deletableLithTemp}"] + lithArgs
    else:
        # loop is being run standalone
        lithtmp = logPrefix.parent / f"{logPrefix.stem}-lith-tmp"
        Path.mkdir(lithtmp)
        lithArgs = [f"--tempdir={lithtmp}"] + lithArgs
    lithlogfn = (logPrefix.parent / f"{logPrefix.stem}-lith-out").with_suffix(".txt")
    print(f"Preparing to run Lithium, log file {lithlogfn}")
    print(" ".join(quote(str(x)) for x in runlithiumpy + lithArgs))
    with io.open(str(lithlogfn), "w", encoding="utf-8", errors="replace") as f:
        subprocess.run(runlithiumpy + lithArgs, check=False, stderr=subprocess.STDOUT, stdout=f)
    print("Done running Lithium")
    if deletableLithTemp:
        shutil.rmtree(deletableLithTemp)
    r = readLithiumResult(lithlogfn)  # pylint: disable=invalid-name

    with open(lithlogfn, "rb") as f_in:  # Replace the old gzip subprocess call
        with gzip.open(lithlogfn.with_suffix(".txt.gz"), "wb") as f_out:
            shutil.copyfileobj(f_in, f_out)
    lithlogfn.unlink()

    return r 
Example #16
Source File: lithium_helpers.py    From funfuzz with Mozilla Public License 2.0 5 votes vote down vote up
def pinpoint(itest, logPrefix, jsEngine, engineFlags, infilename,  # pylint: disable=invalid-name,missing-param-doc
             bisectRepo, build_options_str, targetTime, suspiciousLevel):
    # pylint: disable=missing-return-doc,missing-return-type-doc,missing-type-doc,too-many-arguments,too-many-locals
    """Run Lithium and autobisectjs.

    itest must be an array of the form [module, ...] where module is an interestingness module.
    The module's "interesting" function must accept [...] + [jsEngine] + engineFlags + infilename
    (If it's not prepared to accept engineFlags, engineFlags must be empty.)
    """
    lithArgs = itest + [str(jsEngine)] + engineFlags + [str(infilename)]  # pylint: disable=invalid-name

    (lithResult, lithDetails) = reduction_strat(  # pylint: disable=invalid-name
        logPrefix, infilename, lithArgs, targetTime, suspiciousLevel)

    print()
    print("Done running Lithium on the part in between DDBEGIN and DDEND. To reproduce, run:")
    print(" ".join(quote(str(x)) for x in [sys.executable, "-u", "-m", "lithium", "--strategy=check-only"] + lithArgs))
    print()

    if (bisectRepo != "none" and targetTime >= 3 * 60 * 60 and
            build_options_str is not None and testJsShellOrXpcshell(jsEngine) != "xpcshell"):
        autobisectCmd = (  # pylint: disable=invalid-name
            [sys.executable, "-u", "-m", "funfuzz.autobisectjs"] +
            ["-b", build_options_str] +
            ["-p", " ".join(engineFlags + [str(infilename)])] +
            ["-i"] + [str(x) for x in itest]
        )
        print(" ".join(quote(str(x)) for x in autobisectCmd))
        autobisect_log = (logPrefix.parent / f"{logPrefix.stem}-autobisect").with_suffix(".txt")
        with io.open(str(autobisect_log), "w", encoding="utf-8", errors="replace") as f:
            subprocess.run(autobisectCmd, check=False, stderr=subprocess.STDOUT, stdout=f)
        print(f"Done running autobisectjs. Log: {autobisect_log}")

        with io.open(str(autobisect_log), "r", encoding="utf-8", errors="replace") as f:
            lines = f.readlines()
            autobisect_log_trunc = file_manipulation.truncateMid(lines, 50, ["..."])
    else:
        autobisect_log_trunc = []

    return lithResult, lithDetails, autobisect_log_trunc 
Example #17
Source File: inspect_shell.py    From funfuzz with Mozilla Public License 2.0 5 votes vote down vote up
def testBinary(shellPath, args, useValgrind, stderr=subprocess.STDOUT):  # pylint: disable=invalid-name
    # pylint: disable=missing-param-doc,missing-return-doc,missing-return-type-doc,missing-type-doc
    """Test the given shell with the given args."""
    test_cmd = (constructVgCmdList() if useValgrind else []) + [str(shellPath)] + args
    sps.vdump(f'The testing command is: {" ".join(quote(str(x)) for x in test_cmd)}')

    test_env = env_with_path(str(shellPath.parent))
    asan_options = f"exitcode={ASAN_ERROR_EXIT_CODE}"
    # Turn on LSan, Linux-only
    # macOS non-support: https://github.com/google/sanitizers/issues/1026
    # Windows non-support: https://developer.mozilla.org/en-US/docs/Mozilla/Testing/Firefox_and_Address_Sanitizer
    #   (search for LSan)
    if platform.system() == "Linux" and not ("-asan-" in str(shellPath) and "-armsim64-" in str(shellPath)):
        asan_options = "detect_leaks=1," + asan_options
        test_env.update({"LSAN_OPTIONS": "max_leaks=1,"})
    test_env.update({"ASAN_OPTIONS": asan_options})

    test_cmd_result = subprocess.run(
        test_cmd,
        check=False,
        cwd=os.getcwd(),
        env=test_env,
        stderr=stderr,
        stdout=subprocess.PIPE,
        timeout=999)
    out, return_code = test_cmd_result.stdout.decode("utf-8", errors="replace"), test_cmd_result.returncode
    sps.vdump(f"The exit code is: {return_code}")
    return out, return_code 
Example #18
Source File: languages.py    From bob with GNU General Public License v3.0 5 votes vote down vote up
def mangleFingerprints(scriptFragments, env):
        # join the script fragments first
        script = joinScripts(scriptFragments, BashLanguage.glue)

        # do not add preamble for empty scripts
        if not script: return ""

        # Add snippets as they match and a default settings preamble
        ret = [script]
        for n,s in BASH_FINGERPRINT_SNIPPETS:
            if n in script: ret.append(s)
        ret.extend(["set -o errexit", "set -o nounset", "set -o pipefail"])
        for n,v in sorted(env.items()):
            ret.append("export {}={}".format(n, quote(v)))
        return "\n".join(reversed(ret)) 
Example #19
Source File: languages.py    From bob with GNU General Public License v3.0 5 votes vote down vote up
def _resolveContent(self, result):
        tail = ["_BOB_SOURCES[$LINENO]=" + quote(self.sourceName), result]
        return "\n".join(self.prolog + tail) 
Example #20
Source File: languages.py    From bob with GNU General Public License v3.0 5 votes vote down vote up
def _includeLiteral(self, content):
        return quote(content.decode('utf8')) 
Example #21
Source File: console_util.py    From ICML2019-TREX with MIT License 5 votes vote down vote up
def print_cmd(cmd, dry=False):
    if isinstance(cmd, str):  # for shell=True
        pass
    else:
        cmd = ' '.join(shlex.quote(arg) for arg in cmd)
    print(colorize(('CMD: ' if not dry else 'DRY: ') + cmd)) 
Example #22
Source File: jenkins.py    From bob with GNU General Public License v3.0 5 votes vote down vote up
def dumpStepSpec(self, d):
        cmds = []
        if d.isValid():
            spec = StepSpec.fromStep(d, JenkinsJob._envName(d),
                d.getPackage().getRecipe().getRecipeSet().envWhiteList(),
                isJenkins=True).toString()

            cmds.append("_specFile=" + quote(self._specName(d)))
            cmds.append(JENKINS_SCRIPT_START)
            cmds.append(spec)
            cmds.append(JENKINS_SCRIPT_END)
        return cmds 
Example #23
Source File: archive.py    From bob with GNU General Public License v3.0 5 votes vote down vote up
def download(self, step, buildIdFile, tgzFile):
        if not self.canDownloadJenkins():
            return ""

        args = []
        if self.__key: args.append("--key=" + self.__key)
        if self.__sasToken: args.append("--sas-token=" + self.__sasToken)

        return "\n" + textwrap.dedent("""\
            if [[ ! -e {RESULT} ]] ; then
                bob _download azure {ARGS} {ACCOUNT} {CONTAINER} {BUILDID} {SUFFIX} {RESULT} || echo Download failed: $?
            fi
            """.format(ARGS=" ".join(map(quote, args)), ACCOUNT=quote(self.__account),
                       CONTAINER=self.__container, BUILDID=quote(buildIdFile),
                       RESULT=quote(tgzFile), SUFFIX=ARTIFACT_SUFFIX)) 
Example #24
Source File: archive.py    From bob with GNU General Public License v3.0 5 votes vote down vote up
def download(self, step, buildIdFile, tgzFile):
        # only download if requested
        if not self.canDownloadJenkins():
            return ""

        insecure = "" if self.__sslVerify else "-k"
        return "\n" + textwrap.dedent("""\
            if [[ ! -e {RESULT} ]] ; then
                BOB_DOWNLOAD_BID="$(hexdump -ve '/1 "%02x"' {BUILDID}){GEN}"
                BOB_DOWNLOAD_URL={URL}"/${{BOB_DOWNLOAD_BID:0:2}}/${{BOB_DOWNLOAD_BID:2:2}}/${{BOB_DOWNLOAD_BID:4}}{SUFFIX}"
                curl -sSg {INSECURE} --fail -o {RESULT} "$BOB_DOWNLOAD_URL" || echo Download failed: $?
            fi
            """.format(URL=quote(self.__url.geturl()), BUILDID=quote(buildIdFile), RESULT=quote(tgzFile),
                       GEN=ARCHIVE_GENERATION, SUFFIX=ARTIFACT_SUFFIX,
                       INSECURE=insecure)) 
Example #25
Source File: test_downloads_bdd.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def download_open_placeholder(quteproc):
    cmd = '{} -c "import sys; print(sys.argv[1])"'.format(
        shlex.quote(sys.executable))
    quteproc.send_cmd(':download-open {} {{}}'.format(cmd)) 
Example #26
Source File: _utils.py    From tmppy with Apache License 2.0 5 votes vote down vote up
def pretty_print_command(command: Sequence[str]):
    return ' '.join(shlex.quote(x) for x in command) 
Example #27
Source File: lldb.py    From debugger with MIT License 5 votes vote down vote up
def exec(self, path, args=[], **kwargs):
		if not os.access(path, os.X_OK):
			raise DebugAdapter.NotExecutableError(path)
		if subprocess.call(["DevToolsSecurity"]) != 0:
			raise DebugAdapter.PermissionDeniedError('lldb')

		# resolve path to debugserver
		path_debugserver = shutil.which('debugserver')
		if not path_debugserver:
			path_debugserver = '/Library/Developer/CommandLineTools/Library/' + \
			'PrivateFrameworks/LLDB.framework/Versions/A/Resources/debugserver'
		if not os.path.exists(path_debugserver):
			raise DebugAdapter.NotInstalledError('lldb')

		# get available port
		port = gdblike.get_available_port()
		if port == None:
			raise Exception('no available ports')

		# invoke debugserver
		try:
			if kwargs.get('terminal', False):
				dbg_args = [path_debugserver]
				dbg_args.extend(['--stdio-path', '/dev/stdin'])
				dbg_args.extend(['--stdout-path', '/dev/stdout'])
				dbg_args.extend(['--stderr-path', '/dev/stderr'])
				dbg_args.extend(['localhost:%d'%port, shlex.quote(path), '--'])
				dbg_args.extend([shlex.quote(arg) for arg in args])
				DebugAdapter.new_terminal(' '.join(dbg_args))
			else:
				dbg_args = [path_debugserver, 'localhost:%d'%port, path, '--']
				dbg_args.extend(args)
				subprocess.Popen(dbg_args, stdin=None, stdout=None, stderr=None, preexec_fn=gdblike.preexec)
		except Exception:
			raise Exception('invoking debugserver (used path: %s)' % path_debugserver)

		self.target_path_ = path
		self.connect('localhost', port) 
Example #28
Source File: gdb.py    From debugger with MIT License 5 votes vote down vote up
def exec(self, path, args=[], **kwargs):
		if not os.access(path, os.X_OK):
			raise DebugAdapter.NotExecutableError(path)

		# resolve path to gdbserver
		path_gdbserver = shutil.which('gdbserver')
		if not os.path.exists(path_gdbserver):
			raise DebugAdapter.NotInstalledError('gdbserver')

		# get available port
		port = gdblike.get_available_port()
		if port == None:
			raise Exception('no available ports')

		# invoke gdbserver
		try:
			if kwargs.get('terminal', False):
				dbg_args = [path_gdbserver, '--once', '--no-startup-with-shell', 'localhost:%d'%port, shlex.quote(path)]
				dbg_args.extend([shlex.quote(arg) for arg in args])
				DebugAdapter.new_terminal(' '.join(dbg_args))
			else:
				dbg_args = [path_gdbserver, '--once', '--no-startup-with-shell', 'localhost:%d'%port, path]
				dbg_args.extend(args)
				subprocess.Popen(dbg_args, stdin=None, stdout=None, stderr=None, preexec_fn=gdblike.preexec)
		except Exception:
			raise Exception('invoking gdbserver (used path: %s)' % path_gdbserver)

		# connect to gdbserver
		self.connect('localhost', port) 
Example #29
Source File: arg_parser.py    From sacred with MIT License 5 votes vote down vote up
def format_usage(program_name, description, commands=None, options=()):
    """
    Construct the usage text.

    Parameters
    ----------
        program_name : str
            Usually the name of the python file that contains the experiment.
        description : str
            description of this experiment (usually the docstring).
        commands : dict[str, func]
            Dictionary of supported commands.
            Each entry should be a tuple of (name, function).
        options : list[sacred.commandline_options.CommandLineOption]
            A list of all supported commandline options.

    Returns
    -------
        str
            The complete formatted usage text for this experiment.
            It adheres to the structure required by ``docopt``.

    """
    usage = USAGE_TEMPLATE.format(
        program_name=quote(program_name),
        description=description.strip() if description else "",
        options=_format_options_usage(options),
        arguments=_format_arguments_usage(options),
        commands=_format_command_usage(commands),
    )
    return usage 
Example #30
Source File: VisualStudio.py    From bob with GNU General Public License v3.0 5 votes vote down vote up
def __generateBuildme(self, extra, projectRoot, bobRoot):
        buildMe = []
        if sys.platform == 'msys':
            extra = " ".join(quoteBash(e) for e in extra)
            buildMe.append("#!/bin/sh")
            buildMe.append("export PATH=" + quoteBash(os.environ["PATH"]))
            buildMe.append('bob dev "$@" ' + extra)
            quote = quoteBash
        else:
            extra = " ".join(quoteCmdExe(e) for e in extra)
            buildMe.append("@ECHO OFF")
            buildMe.append("cd " + quoteCmdExe(str(projectRoot)))
            buildMe.append(bobRoot + ' dev %* ' + extra)
            quote = quoteCmdExe
        projectCmd = bobRoot + " project -n " + extra + " vs2019 " + quote("/".join(self.rootPackage.getStack())) + \
            " -u --destination " + quote(self.destination) + ' --name ' + quote(self.projectName) + \
            " --uuid " + quote(str(self.uuid))
        # only add arguments which are relevant for .files or .includes. All other files are only modified if not build with
        # update only.
        for i in self.args.additional_includes:
            projectCmd += " -I " + quote(i)
        if self.args.filter:
            projectCmd += " --filter " + quote(self.args.filter)
        for e in self.args.excludes:
            projectCmd += " --exclude " + quote(e)
        for e in self.args.include:
            projectCmd += "--include " + quote(e)
        for e in self.args.start_includes:
            projectCmd += " -S " + quote(e)

        buildMe.append(projectCmd)
        return "\n".join(buildMe)