Пример #1
0
def run_command(tokens):
    """Execute a command line (treat internal and external appropriately"""

    # Cleanup environment
    for var in pseudo_vars:
        if var in os.environ.keys():
            del os.environ[var]

    if tokens[0] == 'exit':
        internal_exit('Bye!')
    elif tokens[0].lower() == 'cd' and [t for t in tokens if t in sep_tokens
                                        ] == []:
        # This is a single CD command -- use our custom, more handy CD
        internal_cd([unescape(t) for t in tokens[1:]])
    else:
        if set(sep_tokens).intersection(tokens) == set([]):
            # This is a simple (non-compound) command
            # Crude hack so that we return to the prompt when starting GUI
            # applications: if we think that the first token on the given command
            # line is an executable, check its PE header to decide whether it's
            # GUI application. If it is, spawn the process and then get on with
            # life.
            cmd = expand_env_vars(tokens[0].strip('"'))
            dir, name = os.path.split(cmd)
            ext = os.path.splitext(name)[1]

            if not ext or ext in exec_extensions:
                # Executable given
                app = cmd
            else:
                # Not an executable -- search for the associated application
                if os.path.isfile(cmd):
                    app = associated_application(ext)
                else:
                    # No application will be spawned if the file doesn't exist
                    app = None

            if app:
                executable = full_executable_path(app)
                if executable and os.path.splitext(
                        executable)[1].lower() == '.exe':
                    # This is an exe file, try to figure out whether it's a GUI
                    # or console application
                    if is_gui_application(executable):
                        import subprocess
                        s = u' '.join([expand_tilde(t) for t in tokens])
                        subprocess.Popen(s.encode(sys.getfilesystemencoding()),
                                         shell=True)
                        return

        # Regular (external) command
        start_time = time.time()
        run_in_cmd(tokens)
        console_window = win32console.GetConsoleWindow()
        if win32gui.GetForegroundWindow(
        ) != console_window and time.time() - start_time > 15:
            # If the window is inactive, flash after long tasks
            win32gui.FlashWindowEx(console_window, win32con.FLASHW_ALL, 3, 750)
Пример #2
0
def run_in_cmd(tokens):
    line_sanitized = ''
    for token in tokens:
        token_sane = expand_tilde(token)
        if token_sane != '\\' and token_sane[1:] != ':\\':
            token_sane = token_sane.rstrip('\\')
        if token_sane.count('"') % 2 == 1:
            token_sane += '"'
        line_sanitized += token_sane + ' '
    line_sanitized = line_sanitized[:-1]
    if line_sanitized.endswith('&') and not line_sanitized.endswith('^&'):
        # We remove a redundant & to avoid getting an 'Unexpected &' error when
        # we append a new one below; the ending & it would be ignored by cmd.exe
        # anyway...
        line_sanitized = line_sanitized[:-1]
    elif line_sanitized.endswith('|') and not line_sanitized.endswith('^|') \
            or line_sanitized.endswith('&&') and not line_sanitized.endswith('^&&'):
        # The syntax of the command is incorrect, cmd would refuse to execute it
        # altogether; in order to we replicate the error message, we run a simple
        # invalid command and return
        print
        os.system('echo |')
        return

    # Run command
    if line_sanitized != '':
        command = u'"'
        command += line_sanitized
        command += u' &set > "' + tmpfile + u'"'
        for var in pseudo_vars:
            command += u' & echo ' + var + u'="%' + var + u'%" >> "' + tmpfile + '"'
        command += u'& <nul (set /p xxx=CD=) >>"' + tmpfile + u'" & cd >>"' + tmpfile + '"'
        command += u'"'
        os.system(command.encode(sys.getfilesystemencoding()))

    # Update environment and state
    new_environ = {}
    env_file = open(tmpfile, 'r')
    for l in env_file.readlines():
        [variable, value] = l.split('=', 1)
        value = value.rstrip('\n ')
        if variable in pseudo_vars:
            value = value.strip('"')
        new_environ[variable] = value
    env_file.close()
    if new_environ != {}:
        for variable in os.environ.keys():
            if not variable in new_environ.keys() \
                   and sorted(new_environ.keys()) != sorted(pseudo_vars):
                del os.environ[variable]
        for variable in new_environ:
            os.environ[variable] = new_environ[variable]
    cd = os.environ['CD'].decode(stdout.encoding)
    os.chdir(cd.encode(sys.getfilesystemencoding()))
Пример #3
0
def run_in_cmd(tokens):
    line_sanitized = ''
    for token in tokens:
        token_sane = expand_tilde(token)
        if token_sane != '\\' and token_sane[1:] != ':\\':
            token_sane = token_sane.rstrip('\\')
        if token_sane.count('"') % 2 == 1:
            token_sane += '"'
        line_sanitized += token_sane + ' '
    line_sanitized = line_sanitized[:-1]
    if line_sanitized.endswith('&') and not line_sanitized.endswith('^&'):
        # We remove a redundant & to avoid getting an 'Unexpected &' error when
        # we append a new one below; the ending & it would be ignored by cmd.exe
        # anyway...
        line_sanitized = line_sanitized[:-1]
    elif line_sanitized.endswith('|') and not line_sanitized.endswith('^|') \
            or line_sanitized.endswith('&&') and not line_sanitized.endswith('^&&'):
        # The syntax of the command is incorrect, cmd would refuse to execute it
        # altogether; in order to we replicate the error message, we run a simple
        # invalid command and return
        print
        os.system('echo |')
        return

    # Run command
    if line_sanitized != '':
        command = u'"'
        command += line_sanitized
        command += u' &set > "' + tmpfile + u'"'
        for var in pseudo_vars:
            command += u' & echo ' + var + u'="%' + var + u'%" >> "' + tmpfile + '"'
        command += u'& <nul (set /p xxx=CD=) >>"' + tmpfile + u'" & cd >>"' + tmpfile + '"'
        command += u'"'
        os.system(command.encode(sys.getfilesystemencoding()))

    # Update environment and state
    new_environ = {}
    env_file = open(tmpfile, 'r')
    for line in [l for l in env_file.readlines() if not l.isspace()]:
        [variable, value] = line.split('=', 1)
        value = value.rstrip('\n ')
        if variable in pseudo_vars:
            value = value.strip('"')
        new_environ[variable] = value
    env_file.close()
    if new_environ != {}:
        for variable in os.environ.keys():
            if not variable in new_environ.keys() \
                   and sorted(new_environ.keys()) != sorted(pseudo_vars):
                del os.environ[variable]
        for variable in new_environ:
            os.environ[variable] = new_environ[variable]
    cd = os.environ['CD'].decode(stdout.encoding)
    os.chdir(cd.encode(sys.getfilesystemencoding()))
Пример #4
0
def run_command(tokens):
    """Execute a command line (treat internal and external appropriately"""

    # Cleanup environment
    for var in pseudo_vars:
        if var in os.environ.keys():
            del os.environ[var]

    if tokens[0] == 'exit':
        internal_exit('Bye!')
    elif is_pure_cd(tokens):
        # This is a single CD command -- use our custom, more handy CD
        internal_cd([unescape(t) for t in tokens[1:]])
    else:
        if set(sep_tokens).intersection(tokens) == set([]):
            # This is a simple (non-compound) command
            # Crude hack so that we return to the prompt when starting GUI
            # applications: if we think that the first token on the given command
            # line is an executable, check its PE header to decide whether it's
            # GUI application. If it is, spawn the process and then get on with
            # life.
            cmd = expand_env_vars(tokens[0].strip('"'))
            dir, name = os.path.split(cmd)
            ext = os.path.splitext(name)[1]

            if not ext or ext in exec_extensions:
                # Executable given
                app = cmd
            else:
                # Not an executable -- search for the associated application
                if os.path.isfile(cmd):
                    app = associated_application(ext)
                else:
                    # No application will be spawned if the file doesn't exist
                    app = None

            if app:
                executable = full_executable_path(app)
                if executable and os.path.splitext(executable)[1].lower() == '.exe':
                    # This is an exe file, try to figure out whether it's a GUI
                    # or console application
                    if is_gui_application(executable):
                        import subprocess
                        s = u' '.join([expand_tilde(t) for t in tokens])
                        subprocess.Popen(s.encode(sys.getfilesystemencoding()), shell=True)
                        return

        # Regular (external) command
        start_time = time.time()
        run_in_cmd(tokens)
        console_window = win32console.GetConsoleWindow()
        if win32gui.GetForegroundWindow() != console_window and time.time() - start_time > 15:
            # If the window is inactive, flash after long t1asks
            win32gui.FlashWindowEx(console_window, win32con.FLASHW_ALL, 3, 750)
Пример #5
0
def run_in_cmd(tokens):
    pseudo_vars = ["CD", "DATE", "ERRORLEVEL", "RANDOM", "TIME"]

    line_sanitized = ""
    for token in tokens:
        token_sane = expand_tilde(token)
        if token_sane != "\\" and token_sane[1:] != ":\\":
            token_sane = token_sane.rstrip("\\")
        if token_sane.count('"') % 2 == 1:
            token_sane += '"'
        line_sanitized += token_sane + " "
    line_sanitized = line_sanitized[:-1]
    if line_sanitized.endswith("&") and not line_sanitized.endswith("^&"):
        # We remove a redundant & to avoid getting an 'Unexpected &' error when
        # we append a new one below; the ending & it would be ignored by cmd.exe
        # anyway...
        line_sanitized = line_sanitized[:-1]
    elif (
        line_sanitized.endswith("|")
        and not line_sanitized.endswith("^|")
        or line_sanitized.endswith("&&")
        and not line_sanitized.endswith("^&&")
    ):
        # The syntax of the command is incorrect, cmd would refuse to execute it
        # altogether; in order to we replicate the error message, we run a simple
        # invalid command and return
        print
        os.system("echo |")
        return

    # Cleanup environment
    for var in pseudo_vars:
        if var in os.environ.keys():
            del os.environ[var]

    # Run command
    if line_sanitized != "":
        command = u'"'
        command += line_sanitized
        command += u' &set > "' + tmpfile + u'"'
        for var in pseudo_vars:
            command += u" & echo " + var + u'="%' + var + u'%" >> "' + tmpfile + '"'
        command += u'& <nul (set /p xxx=CD=) >>"' + tmpfile + u'" & cd >>"' + tmpfile + '"'
        command += u'"'
        os.system(command.encode(sys.getfilesystemencoding()))

    # Update environment and state
    new_environ = {}
    env_file = open(tmpfile, "r")
    for l in env_file.readlines():
        [variable, value] = l.split("=", 1)
        value = value.rstrip("\n ")
        if variable in pseudo_vars:
            value = value.strip('"')
        new_environ[variable] = value
    env_file.close()
    if new_environ != {}:
        for variable in os.environ.keys():
            if not variable in new_environ.keys() and sorted(new_environ.keys()) != sorted(pseudo_vars):
                del os.environ[variable]
        for variable in new_environ:
            os.environ[variable] = new_environ[variable]
    cd = os.environ["CD"].decode(stdout.encoding)
    os.chdir(cd.encode(sys.getfilesystemencoding()))