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

drunk user
  • 65
  • 1
  • 9
  • 1
    Is your working directory named "numpy"? rename it. and also, always use the `if __name__ == '__main__'` idiom. – shx2 Feb 20 '15 at 11:00
  • @shx2: not the directory, but the exe file :) renamed it, thx – drunk user Feb 20 '15 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. – unutbu Feb 20 '15 at 11:04
  • @shx2: would it be better to use 'import numpy' then? you can of course post this as an answer – drunk user Feb 20 '15 at 11:13

1 Answers1

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.

shx2
  • 61,779
  • 13
  • 130
  • 153