0

I ran a script using "python -i" from the command line. The script ran as I expected and I end up in interactive mode, as expected.

Now, however, I want to use a command from the scipy.signal package, so I type:

>>> from scipy import signal

For some reason, this triggers the interpreter to run the whole script again from the start.

Why does this happen? And how should I avoid it?

sghys
  • 1
  • 1
  • Is your script file named `scipy.py` perhaps? – Martijn Pieters Jan 19 '19 at 12:33
  • If not, what filename did you use? It is probably being imported somewhere. – Martijn Pieters Jan 19 '19 at 12:34
  • the script was named timeit.py, which is apparantly a python module. However, I changed it to test.py and the same thing keeps happening: `$ python -i test.py Calculate Spectral Densities Correlate time np.correlate() : 0.04867911338806152 /anaconda3/lib/python3.7/site-packages/numpy/core/numeric.py:501: ComplexWarning: Casting complex values to real discards the imaginary part return array(a, dtype, copy=False, order=order) >>> from scipy import signal Calculate Spectral Densities Correlate time np.correlate() : 0.05021977424621582 >>> ` – sghys Jan 19 '19 at 13:05
  • Sorry, that formatting looks aweful. Basically, the _Calculate Spectral Densities Correlate time np.correlate() : 0.04867911338806152_ part is output of the script (the number being the computational time using the time-module, so it's not an issue if the numbers aren't the same) – sghys Jan 19 '19 at 13:08

1 Answers1

1

When you import a file the whole file is read in and executed. This is the same whether you use from file import function or just import file.

You should place any code you don't want to run when it is imported in a block like this:

if __name__ = '__main__':
    your code here

Your function definitions that you wish to import should be outside this block, as they need to be loaded and executed to be imported and available for use.

See this duplicate question which explains this in further detail.

Nick Perkins
  • 1,327
  • 2
  • 12
  • 25
  • I am importing the scipy.signal module, which is a signal processing module (which I did not write): https://docs.scipy.org/doc/scipy/reference/signal.html – sghys Jan 19 '19 at 12:58