Long Live Python!

Skip Montanaro skip at pobox.com
Thu Jul 12 23:52:03 CEST 2001


    Bruce> """
    Bruce> import os
    Bruce> os.system('cat file*1 file*2 file*3 | tee file4 | wc -cwl >> file5')
    Bruce> """

    Bruce> Is Ok when you are in the Python Interpreter, but would you do...

    Bruce> $ python -c "import os;os.system('cat file*1 file*2 file*3 | tee file4 | wc -cwl >> file5')"

    Bruce> ...from the command line that comes up when you login?

Well, no, but I might run this file as "python mycode.py" (ten-minute hack -
buyer beware) and type either Python or shell commands at the interpreter
prompt:

    import code

    class Console(code.InteractiveConsole):
        def runsource(self, source, filename="<input>", symbol="single",rec=0):
            import os
            from code import softspace
            import sys
            self.locals.update({"os": os, "softspace": softspace, "sys": sys})
            try:
                from codeop import compile_command
                code = compile_command(source, filename, symbol)
            except SyntaxError:
                source = """x = os.system('''%s''')""" % source
                return self.runsource(source, filename, symbol, rec=1)
            except (OverflowError, ValueError):
                # Case 1
                self.showsyntaxerror(filename)
                return 0

            if code is None:
                # Case 2
                return 1

            # Case 3
            try:
                exec code in self.locals
            except SystemExit:
                raise
            except:
                if rec == 1:
                    raise
                source = """x = os.system('''%s''')""" % source
                return self.runsource(source, filename, symbol, rec=1)
            else:
                if softspace(sys.stdout, 0):
                    print
            return 0

    Console().interact()

The output looks like

    % python mycode.py
    Python 2.1.1c1 (#13, Jul 10 2001, 17:30:38) 
    [GCC 2.96 20000731 (Linux-Mandrake 8.0 2.96-0.48mdk)] on linux2
    Type "copyright", "credits" or "license" for more information.
    (Console)
    >>> wc -l /etc/termcap
      16412 /etc/termcap
    >>> f = open("/etc/termcap")
    >>> f.readlines()[10]
    '# Please e-mail changes to terminfo at thyrsus.com; the old termcap at berkeley.edu\n'
    >>> 

;-)

-- 
Skip Montanaro (skip at pobox.com)
(847)971-7098




More information about the Python-list mailing list