0

I have a template directory where my test.py file is present.

Path to test.py dir is - /user/document/test1/template/test.py

(I have __init__.py as well)

contest of test.py is

import os

test_dict = {
   'number' : ['1', '2'],
   'values' : ['a', 'b', 'c']
}

What I am trying in other script is

script.py

path to script.py is - /user/document/home/script.py

import os

os.chdir('/user/document/test1/')

exec('from template.test import test_dict')

print(test_dict)

And in the same dir I have another file called run.py

path to run.py is - /user/document/home/run.py

import subprocess

subprocess.Popen('python /user/document/home/script.py ',shell=True,stderr=subprocess.PIPE,stdout=subprocess.PIPE,universal_newlines=True)

Now when I run run.py (with pdb debugger) I see the exec from script.py is not able to find the template module.

How do I make it right? I want test_dict from test.py inside script.py

bad_coder9042093
  • 307
  • 3
  • 13
  • Maybe it's just a typo in this post but it seems like you are missing a closing apostrophe in: os.chdir('/user/document/test1/) – jlipinski Apr 27 '23 at 07:54
  • 1
    The subprocess is completely independent from the parent; you can't see the internal variables from a C program like the Bash interpreter either, unless it specifically provides an API for querying it. Running Python as a subprocess of itself is often an antipattern, anyway. What you seem to be trying to do is easily achieved by `import`ing the code you want to run into the current script (though it might require some refactoring before you can do that). – tripleee Apr 27 '23 at 07:54
  • Instead of `os.chdir` add the path to `sys.path`. – Michael Butscher Apr 27 '23 at 07:57
  • @jlipinski yes there was typo when I am posting this. But I scrips its correct. – bad_coder9042093 Apr 27 '23 at 07:58
  • Also, almost certainly avoid `shell=True` here. See [Actual meaning of `shell=True` in subprocess](https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess) – tripleee Apr 27 '23 at 07:59

0 Answers0