0

Assume having a directory structure like this:

src\
    foo1.py
    Dir\
        foo2.py

When I use the below code inside foo1.py, I have no problem in running:

import os
os.chdir("Dir")
exec(open("./foo2.py").read())
os.chdir("..")

But when I changed it to this:

import os
def test():
    os.chdir("Dir")
    exec(open("./foo2.py").read())
    os.chdir("..")

test()

Error accurs:

Traceback (most recent call last):
  File "foo1.py", line 8, in <module>
    test()
  File "foo1.py", line 5, in test
    exec(open("./foo2.py").read())
  File "<string>", line 134, in <module>
NameError: name 'resistorLength' is not defined

Anything I am missing?

Thank you.

Mojtaba
  • 19
  • 1
  • 4
  • Might help to know what is in `foo2.py`. Might help to know what you get returned from `open("./foo2.py").read()`. – Scott Hunter Jul 11 '17 at 12:04
  • if both are python scripts, why run them via `exec` ? you could just do a simple import and run the functions you want this way (see here https://stackoverflow.com/questions/1186789/what-is-the-best-way-to-call-a-python-script-from-another-python-script) – Chris Jul 11 '17 at 12:05
  • @ScottHunter foo2.py is rather a long file. but the main commands are importing an excel file using openpyxl module and then editing it. Some file copying are also taking place at last lines of the file. – Mojtaba Jul 12 '17 at 03:55
  • @Chris I have done all possible solutions to call a python file from another, specifically the one you mentioned. but the same problem exists. – Mojtaba Jul 12 '17 at 03:58
  • @ScottHunter running open("./foo2.py").read() won't run alone since it needs changing the working directory in before hand. – Mojtaba Jul 12 '17 at 03:59
  • @user179892: I didn't ask you to run it alone; I asked you to check what it returns. While you are at it, you might want to check what `open("./foo2.py")` returns. – Scott Hunter Jul 12 '17 at 09:01

1 Answers1

0

An alternate solution was to use batch scripts to run my python files inside the main python file. I made a batch file like this:

runFoo2.bat

cd Dir
python.exe foo2.py
cd ..

And then changed foo1.py so that:

foo1.py

from subprocess import call
def runFoo2():
    p = call("runFoo2.bat")

Everything worked fine afterwards.

Mojtaba
  • 19
  • 1
  • 4