简体   繁体   中英

Importing from python interactive mode

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM