Skip to content
Advertisement

python: numpy runs script twice

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement