-3

Let me first say that I'm a newbie to python, and I've written a python shell named test.py. The content is as follows:

#!/usr/bin/python
import os
cur_dir = os.getcwd();
print 'hello world' > cur_dir+"/test.log" 2>&1

When I run test.py by "python test.py", it says:

File "test.py", line 4
print 'hello world' > cur_dir+"/test.log" 2>&1
                                          ^
SyntaxError: invalid syntax

Could anyone give me some idea? Thanks!

P.S. what I want is to write a string in test.log file. That's all. As I said first, I'm REALLY new to python, so please don't be so harsh to me :), I'm gonna read through the tutorial first to have a glimpse of python, Thanks to all you guys!

Judking
  • 6,111
  • 11
  • 55
  • 84

2 Answers2

3

You are using invalid syntax. As a result Python gives you the error:

SyntaxError: invalid syntax

To fix this, stop using the invalid syntax.

Also in the future, explain what you are trying to achieve, and your answers are likely to tell you how to achieve that.

The invalid syntax looks like it's a bash redirection of stderr to stdout which makes no sense in the context above, so it's not possible to figure out what you are actually trying to do.

To write to a file you do this:

thefile = open('path_to_the_file', 'wt')
thefile.write('The file text.\n')

However, to do logging, you are better off using the logging module.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
1

Use '>>' with print to redirect it to an alternate stream.

See How to print to stderr in Python?

Community
  • 1
  • 1
bluedog
  • 935
  • 1
  • 8
  • 24