0

Let's that I have the following Python script script.py:

a = 1
b = 10

for i in range(b):
    a += 1

print(a)

I know that I can use globals() inside this script.py in order to show the namespace:

{'__file__': 'counter.py', '__doc__': None, 'i': 9, '__spec__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000027C8D9402E8>, '__name__': '__main__', '__cached__': None, 'b': 10, 'a': 11, '__package__': None, '__builtins__': <module 'builtins' (built-in)>}

I wonder whether you can somehow emulate globals() from outside the script.py? In other words, I want to run other_script.py and see the script.py's globals() output. Is import counter somehow useful?

EDIT: if possible, can script.py's globals output be updated with each increment of i in the for loop?

3
  • Can you give some more deployment details? Are script.py and other_script.py started separately (ie as completely separate processes) or do you intend for one to start the other? As completely sperrate processes I don't believe you should be able to do much but you may have some options if one is the subprocess of the other using pythons multiprocessing module. Commented Mar 18, 2019 at 11:55
  • script.py and other_script.py are completely separate processes. Commented Mar 19, 2019 at 5:26
  • This may be an OS dependant problem since you want one process to access the memory of another. There are ways to do this but very few are easy. My advice is to not reinvent the wheel: use a database (a simple k/v store should be fine like redis) or set up a simple Http server in your host script. Commented Mar 19, 2019 at 12:26

1 Answer 1

1

The problem with import counter is that the namespace inside counter.py will be changed to your current namespace, since you are importing it inside your current namespace.

However, if all you want to do is simply see the counter.py output, you could just use the exec() function to execute it separately. This will not change its namespace.

Example:

In counter.py:

a = 1
b = 10

for i in range(b):
    print('\na = ', a)
    print('globals = ', globals())
    a += 1

print('\na = ', a)
print('globals = ', globals())

In other_script.py:

exec(open('counter.py').read())
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the answer. Let's assume that there're no print statements in the counter.py file. Is it still possible to see the values of variables a, b and i? The current approach with exec(open('counter.py').read()) produces empty output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.