0

I am trying to follow a book step-by-step but I am either getting nothing back or getting errors.

Can anyone tell me what's going on?

import sys

class RedirectStdoutTo:
    def _init_(self, out_new):
        self.out_new=out_new

    def _enter_(self):
        self.out_old= sys.stdout
        sys.stdout = self.out_new

    def _exit_(self, *args):
        sys.stdout = self.out_old

print('A')
with open('out.log', mode='w', encoding='utf-8') as a_file, RedirectStdoutTo(a_file):
    print('B')
print('C')

And when I run in Python, I write python log.py

It returns an error saying:

File "<stdin>", line 1
    python ilog.py
              ^
SyntaxError: invalid syntax
Michael Currie
  • 13,721
  • 9
  • 42
  • 58
Annie
  • 47
  • 1
  • 2
  • 8
  • Are you trying to run a Python script from within the Python interpreter, using terminal-style commands? – TigerhawkT3 Aug 20 '15 at 22:07
  • What Operating System are you attempting to run this on? – cogle Aug 20 '15 at 22:12
  • 1
    Doing `python log.py` within the Python interpreter instead of at your OS's console/terminal is like starting your car and telling it to get you a sandwich instead of telling your friend to take your car and go get you a sandwich. – TigerhawkT3 Aug 20 '15 at 22:19
  • Oh okay. Thank you. That was the problem. – Annie Aug 20 '15 at 22:29
  • 1
    If you want to start your script from commandline make sure you read about the Python shebang: http://stackoverflow.com/questions/6908143/should-i-put-shebang-in-python-scripts-and-what-form-should-it-take – user937284 Aug 20 '15 at 22:45
  • 1
    Note also that it should be `__init__` (et. al), not `_init_`. You're missing a set of underscores. – Adam Smith Aug 20 '15 at 22:46

1 Answers1

1

The problem is not with your script, but in how you invoke it. As far as I understood, you start python and then type in python log.py. This is wrong - you need to start python with log.py as argument, not type this in to already started Python interactive session.

If you start python from OS X terminal (or similar command-line prompt), then instead of saying python say python log.py, while you're in the same directory as your log.py file.

The python log.py command is not Python, but a shell command. It's meant for your OS X terminal's bash prompt, not for Python itself.

drdaeman
  • 11,159
  • 7
  • 59
  • 104
  • I am using OS X terminal. – Annie Aug 20 '15 at 22:26
  • I first typed in python to start it. And then to access the file, I write: python log.py – Annie Aug 20 '15 at 22:27
  • Good, then it's simple. Just type `python log.py` instead of just `python` right in OS X terminal, when you want to start Python. See, the idea is to invoke Python, giving it filename of your script as *argument*, not just starting Python (this invokes so-called interactive shell) and then trying to tell it to load something. – drdaeman Aug 20 '15 at 22:30