1

I try to run a script in Python3 by exec() function.

I'm studying Python with the book 'Learning Python', O'Reilly 5th Edition. In the "CHAPTER 2 How Python Runs Programs" there is a method to like this:

>>> exec(open('script1.py').read())

This is my file script1.py

# A first script in python.
import sys
print(sys.platform)
print(2 **100)
x = 'Spam!'
print(x * 8)
input()

The expected output is:

win32
1267650600228229401496703205376
Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!

In the work I only can use WinXP :-(

But the real output in Python3 is:

>>> exec(open('script1.py').read())

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    # A first script in python.
         ^
SyntaxError: invalid character in identifier
>>>

And the output in Python2 is:

>>> exec(open('script1.py').read())
win32
1267650600228229401496703205376
Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 7, in <module>
  File "<string>", line 0

    ^
SyntaxError: unexpected EOF while parsing
>>>

I don't understand why that isn't working like the book says.

agc
  • 7,973
  • 2
  • 29
  • 50
Trimax
  • 2,413
  • 7
  • 35
  • 59

1 Answers1

2

The problem is in your editor, that adds an ''incorrect symbol'' (actually, the symbol is correct per se) at the beginning of the file. Please check it.

If you want to check this conjecture, please do

print open('script1.py').read(1)

in the python repl.

It is probably BOM in the file (thanks @devnull).

If it is so, you can open the file with encondig utf-8-sig:

 open('script1.py', encoding='utf-8-sig')

More on that you can read here:

What is BOM (Byte Order Mark), you can find here:

And of course, you must avoid BOMs in your scripts in the future. Please check settings of your editor, and make sure it doesn't create BOMs when saving scripts.

Community
  • 1
  • 1
Igor Chubin
  • 61,765
  • 13
  • 122
  • 144
  • @Igor Chubin the output is the char ` I used Notepad++ to create it and coding in UTF-8. I've change coding to UTF-8 without BOM and saved it. Now, It Works!! Thanks guy, and @devnull too!! – Trimax Jan 20 '14 at 15:01
  • @Trimax: Yes, the conjecture was correct. Please check my update. – Igor Chubin Jan 20 '14 at 15:02
  • The damn coding (source of a lot of bugs). @IgorChubin thanks again! – Trimax Jan 20 '14 at 15:10