Question

I'm using python 2.7 / pythonxy / Spyder. I've got a.py and b.py and I want to call a def from a.py in b.py. So I write "import a" in b.py but I get a load of errors. The errors appear to be caused by the fact that the numpy functions are not recognized in a.py even though they are by default preloaded by Spyder.

From other questions and answers I get that the silly solution is to import the functions in a.py. So I start adding them in a.py by typing from numpy import xxxxxx. But this still leaves me errors. The first 2 are:

  • "return round(a-b, 2) - TypeError: only length-1 arrays can be converted to Python scalars".
  • "d2=sorted(d2,key=lambda kv: kv[2],reverse=True - ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()"

When I just run a.py I don't get these errors, so I know the code is right. What I don't know is what I have to do the be allowed to import a.py which contains these lines?

Was it helpful?

Solution

To import a python file into another python file, the best way is

try:
    __import__(sys.argv[1])
except Exception as e:
    my_traceback = sys.exc_info()[2]

Here you send the file name as a parameter to the other python file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top