0

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?

Guy dV
  • 3
  • 1
  • Why are you calling `sorted` on an array? – user2357112 Aug 08 '13 at 21:42
  • d2 is not an array. It's a list, but based on the error it gives, Python doesn't understand it is a list? – Guy dV Aug 09 '13 at 07:43
  • If `d2` isn't an array, it's most likely a list of arrays (or a list of lists of arrays, or anything where `d2[0][2]` would be an array). There's no good way to define an ordering relationship on arrays, so you can't sort them. – user2357112 Aug 09 '13 at 14:45
  • Hmm, true it is a list of arrays. In any case, after using the code suggested by Aakash Anuj, the code now works. Thanks. – Guy dV Aug 10 '13 at 08:07

1 Answers1

-1

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.

Aakash Anuj
  • 3,773
  • 7
  • 35
  • 47