0

Trying to move my application to Python 3.4...

My code:

    def Continue(self):
        exec(open(b"file.py").read())

My error:

TypeError: can't use a string pattern on a bytes-like object

My (miss)understanding is that by prefixing the filename string with a 'b' I am turning it into the required bytes like object.

Can anyone elighten me?

Ben Mayo
  • 1,285
  • 2
  • 20
  • 37
  • I think the file is read in as bytes. Try exec(open("file.py").read().decode("ascii"))) or encode. You can also try decode("ascii", "ignore") which will ignore errors that occur. – justengel Dec 19 '14 at 13:19
  • Thanks - error is 'str object has no attribute decode' – Ben Mayo Dec 19 '14 at 13:32
  • I'm not certain if I was sufficiently clear with my question - I'm trying to call a Python script from within another. In Python 2.x I'd have simply used exec("file.py") – Ben Mayo Dec 19 '14 at 13:33

1 Answers1

1

What is an alternative to execfile in Python 3?

Basically open the file, read it, compile the code, and run it.

with open("somefile.py") as f:
    code = compile(f.read(), "somefile.py", 'exec')
    exec(code, global_vars, local_vars)
Community
  • 1
  • 1
justengel
  • 6,132
  • 4
  • 26
  • 42