LINUX.ORG.RU

История изменений

Исправление true_admin, (текущая версия) :

достаточно совсем немного времени, что-бы освоить все операторы питона. Их там немного, ибо «один путь».

А теперь давай посмотрим что будет если этот путь пролегает в стороне от того что тебе нужно:

# we're being run as a stand-alone script, fire up a REPL
if __name__ == "__main__":
    globs = globals()
    f_globals = {}
    for k in ["__builtins__", "__doc__", "__name__", "__package__"]:
        f_globals[k] = globs[k]
    env = Environment(f_globals)
    run_repl(env)

# we're being imported from somewhere
else:
    frame, script, line, module, code, index = inspect.stack()[1]
    env = Environment(frame.f_globals)


    # are we being imported from a REPL?
    if script.startswith("<") and script.endswith(">") :
        self = sys.modules[__name__]
        sys.modules[__name__] = SelfWrapper(self)

    # we're being imported from a script
    else:

        # we need to analyze how we were imported
        with open(script, "r") as h: source = h.readlines()
        import_line = source[line-1]

        # this it the most magical choice.  basically we're trying to import
        # all of the system programs into our script.  the only way to do
        # this is going to be to exec the source in modified global scope.
        # there might be a less magical way to do this...
        if "*" in import_line:
            # do not let us import * from anywhere but a stand-alone script
            if frame.f_globals["__name__"] != "__main__":
                raise RuntimeError("Cannot import * from anywhere other than \
a stand-alone script.  Do a 'from pbs import program' instead. Please see \
\"Limitations\" here: %s" % PROJECT_URL)

            warnings.warn("Importing * from pbs is magical and therefore has \
some limitations.  Please become familiar with them under \"Limitations\" \
here: %s  To avoid this warning, use a warning filter or import your \
programs directly with \"from pbs import <program>\"" % PROJECT_URL,
RuntimeWarning, stacklevel=2)

            # we avoid recursion by removing the line that imports us :)
            source = "".join(source[line:])

            exit_code = 0
            try: exec(source, env, env)
            except SystemExit as e: exit_code = e.code
            except: print(traceback.format_exc())

            # we exit so we don't actually run the script that we were imported
            # from (which would be running it "again", since we just executed
            # the script with exec
            exit(exit_code)

        # this is the least magical choice.  we're importing either a
        # selection of programs or we're just importing the pbs module.
        # in this case, let's just wrap ourselves with a module that has
        # __getattr__ so our program lookups can be done there
        else:
            self = sys.modules[__name__]
            sys.modules[__name__] = SelfWrapper(self)

Сможешь понять что оно делает?

На самом деле есть способ гораздо проще, но суть не меняется: простота она бывает обманчива. Вроде, питон простой язык, но не всегда простые вещи просто делаются. Т.е. он может сильно ограничивать полёт фантазии.

Исходная версия true_admin, :

достаточно совсем немного времени, что-бы освоить все операторы питона. Их там немного, ибо «один путь».

А теперь давай посмотрим что будет если этот путь пролегает в стороне от того что тебе нужно:

# we're being run as a stand-alone script, fire up a REPL
if __name__ == "__main__":
    globs = globals()
    f_globals = {}
    for k in ["__builtins__", "__doc__", "__name__", "__package__"]:
        f_globals[k] = globs[k]
    env = Environment(f_globals)
    run_repl(env)

# we're being imported from somewhere
else:
    frame, script, line, module, code, index = inspect.stack()[1]
    env = Environment(frame.f_globals)


    # are we being imported from a REPL?
    if script.startswith("<") and script.endswith(">") :
        self = sys.modules[__name__]
        sys.modules[__name__] = SelfWrapper(self)

    # we're being imported from a script
    else:

        # we need to analyze how we were imported
        with open(script, "r") as h: source = h.readlines()
        import_line = source[line-1]

        # this it the most magical choice.  basically we're trying to import
        # all of the system programs into our script.  the only way to do
        # this is going to be to exec the source in modified global scope.
        # there might be a less magical way to do this...
        if "*" in import_line:
            # do not let us import * from anywhere but a stand-alone script
            if frame.f_globals["__name__"] != "__main__":
                raise RuntimeError("Cannot import * from anywhere other than \
a stand-alone script.  Do a 'from pbs import program' instead. Please see \
\"Limitations\" here: %s" % PROJECT_URL)

            warnings.warn("Importing * from pbs is magical and therefore has \
some limitations.  Please become familiar with them under \"Limitations\" \
here: %s  To avoid this warning, use a warning filter or import your \
programs directly with \"from pbs import <program>\"" % PROJECT_URL,
RuntimeWarning, stacklevel=2)

            # we avoid recursion by removing the line that imports us :)
            source = "".join(source[line:])
--------
            exit_code = 0
            try: exec(source, env, env)
            except SystemExit as e: exit_code = e.code
            except: print(traceback.format_exc())

            # we exit so we don't actually run the script that we were imported
            # from (which would be running it "again", since we just executed
            # the script with exec
            exit(exit_code)

        # this is the least magical choice.  we're importing either a
        # selection of programs or we're just importing the pbs module.
        # in this case, let's just wrap ourselves with a module that has
        # __getattr__ so our program lookups can be done there
        else:
            self = sys.modules[__name__]
            sys.modules[__name__] = SelfWrapper(self)

Сможешь понять что оно делает?

На самом деле есть способ гораздо проще, но суть не меняется: простота она бывает обманчива. Вроде, питон простой язык, но не всегда простые вещи просто делаются. Т.е. он может сильно ограничивать полёт фантазии.