Using 'exec' function to run script in the interpreter shell
Question: 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 expectec 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.


Answer: 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:

  * [Reading Unicode file data with BOM chars in Python](http://stackoverflow.com/questions/13590749/reading-unicode-file-data-with-bom-chars-in-python)

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

  * <http://en.wikipedia.org/wiki/Byte_order_mark>

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.

