Python import works, read text from file and exec doesn't

Rodney Price

I have a file data.py in directory exectest containing

testd = { 1: "one", 2: "two" }

When I type import data, I get

In [5]: import data
In [6]: data.testd
Out[6]: {1: 'one', 2: 'two'}

as expected. However, I have another file exectest.py containing

from pathlib import Path
def read_data():
    path = Path.cwd() / "data.py"
    text = path.read_text()
    print(f"{text=}")
    exec(text)
    return testd

When I type the following, I get an error

In [7]: exectest.read_data()
text='\ntestd = { 1: "one", 2: "two" }\n'
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[7], line 1
----> 1 exectest.read_data()

File ~/working/tmp/exectest/exectest.py:9, in read_data()
      7 print(f"{text=}")
      8 exec(text)
----> 9 return testd

NameError: name 'testd' is not defined

From the interpreter, typing in the statements in read_data() directly reads the text in data.py and evaluates it correctly,

In [10]: from pathlib import Path

In [11]: path = Path.cwd() / "data.py"

In [12]: text = path.read_text()

In [13]: text
Out[13]: '\ntestd = { 1: "one", 2: "two" }\n'

In [14]: exec(text)

In [15]: testd
Out[15]: {1: 'one', 2: 'two'}

I don't understand why import data works, and typing statements directly into the interpreter works, but packaging those statements up into a function does not. Any ideas?

nokla

The variables created inside an exec call are by default local to the scope of that exec call. They do not become global variables, which is why you're encountering a NameError when trying to access testd outside of the exec call.

You can pass a locals dictionary to the exec function like so:

from pathlib import Path
def read_data():
    path = Path.cwd() / "data.py"
    text = path.read_text()
    print(f"{text=}")
    local_vars = {}
    exec(text, {}, local_vars)
    testd = local_vars.get('testd', None)
    return testd

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

from . import models works, but import models doesn't

Import specific text from a file to list in Python

Python - Read from text file and put into a list

Import equation from text file in Python

Running shell script from terminal works but doesn't work when running from PHP shell_exec

read and split information from text file python

Is using exec() to execute code read from a text file bad practice?

How to read input() from a text file in Python

python read from text file line by line

can't import python dictionary from a text file

Can't import numpy module into python file, but it works with terminal

c++ code to sort text file doesn't works

find works, but find -exec doesn’t

read numbers from text file python

Python (scipy) import time from text file

Python 3: Regex doesn't work when read text from file

I'm trying to implement a quote system in mIRC for my Twitch bot, reading from the text file works, but adding doesn't

Python read from specific parts of a text file

Downloading a file in php doesn't work for pdf but works for text files

Python doesn't read whole txt file

Can't import a file from a python package

Why works "import file", but "from file import class" won't work?

Full path to import works but file reference doesn't

Python import via exec does not work, while hardcoded import works

python, trying to read a file but it doesn't find it

Read Python list from a Text file

How to read text from a file using Python?

read values from text file in python

Can't read from user after using exec <file to read from file