2

when I import numpy to my python script, the script is executed twice. Can someone tell me how I can stop this, since everything in my script takes twice as long?

Here's an example:

#!/usr/bin/python2

from numpy import *

print 'test_start'

lines = open('test.file', 'r').readlines()
what=int(lines[0])+2
nsteps = len(lines)/what
atom_list=[]
for i in range(0,nsteps*what):
  atom_list.append(lines[i].split())

del atom_list[:]
print 'test_end'

And the output is:

test_start
test_end
test_start
test_end

So, is my script first executed with normal python and then with numpy again? Maybe I should say that I have not worked with numpy yet and just wanted to start and test it.

Cheers

4
  • 1
    Is your working directory named "numpy"? rename it. and also, always use the if __name__ == '__main__' idiom. Commented Feb 20, 2015 at 11:00
  • @shx2: not the directory, but the exe file :) renamed it, thx Commented Feb 20, 2015 at 11:03
  • You might also want to avoid using from numpy import * since this overwrites common Python builtins like sum and any and all with the NumPy functions of the same names, leading to (potentially) surprising behavior. Commented Feb 20, 2015 at 11:04
  • @shx2: would it be better to use 'import numpy' then? you can of course post this as an answer Commented Feb 20, 2015 at 11:13

1 Answer 1

4

Your script, being named numpy.py, unintentionaly imports itself. Since module-level code gets executed when imported, the import line causes it to run, then once the imoprt is completed, it runs the rest again.

(An explanation about why a script can import itself)

Suggestions:

  1. rename your script to something other than numpy.py
  2. use the if __name__=='__main__' idiom (you should always use it in your scripts)

Other than that, as already pointed out, from numpy import * is strongly discouraged. Either use import numpy or the common import numpy as np.

Sign up to request clarification or add additional context in comments.

Comments

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.