0

I have 2 Python scripts:

ScriptSmall.py:

a=9

ScriptBig.py:

a=5
print(a)

f=open('ScriptSmall.py')
exec(f.read())
f.close

print(a)

When I run ScriptBig.py in the terminal as python3 ScriptBig.py, the terminal prints out:

$python3 ScriptBig.py
5
5

I would like it to print out 5 and then 9. What I am doing wrong?

Stefano
  • 359
  • 1
  • 5
  • 16
  • When you use `exec()`, it's just like if the code there were in the script. It doesn't have its own scope. – Barmar May 24 '18 at 19:14
  • What's the point of executing `ScriptSmall.py` if you don't want to get its variable assignments? That's all it does. – Barmar May 24 '18 at 19:15
  • 1
    Why are you using `exec()` instead of `import`? Then the variables will be scoped to the module name. – Barmar May 24 '18 at 19:15
  • @Barmar this code *should* work though, since it is working with `globals` – juanpa.arrivillaga May 24 '18 at 19:38
  • @juanpa.arrivillaga That's the reason for the problem. There's only one global variable `a`, so when `ScriptSmall.py` assigns to it, it updates the variable in `ScriptBig.py` as well. – Barmar May 24 '18 at 19:39
  • @Kasramvd There are no local variables in this script, it's all globals. – Barmar May 24 '18 at 19:40
  • @Barmar No, it doesn't. Note, `ScriptSmall.py` *never runs*. It's basically a text-file which the second script loads as a string `"a = 9\n"` and executes. I ran this on my computer and it prints `5` and then `9` – juanpa.arrivillaga May 24 '18 at 19:41
  • @Stefano I cannot reproduce your output. I get 5 and 9. Are you **sure** this is exactly the code you are running? The *main problem I see is that you are using `exec` to begin with*, but I do not see the output you are describing, I see the output you expect. – juanpa.arrivillaga May 24 '18 at 19:43
  • @Barmar Yes but the answer is still there. `exec` has its own scope and changing an immutable variable inside its scope doesn't affect the global namespace. – Mazdak May 24 '18 at 19:53
  • @juanpa.arrivillaga. Yes, you are right. My actual code is has one more nested call. I didn't add that one for sake of clarity but it seems that it resulted the opposite. I found my answer in the link that Kasramvd pointed out. Thank you all for your comments. I am fairly new in Python and they helped. – Stefano May 24 '18 at 23:15

0 Answers0