Cannot import my own module when running script in Spyder

跟風遠走 提交于 2020-01-23 17:33:31

问题


According to the official Python documentations or to this post importing own modules into scripts is quite easy. Basically I just need to create my .py files, save them in one directory and I can import them using just

from my_module import my_function

It is exactly what I did in my Project. I wrote two scripts and saved them inside one directory. I would like to use some functions from them in third script (again it is saved in the same directory). As in the picture below.

Now I import WebScraper.py in the following way

As you can see in the picture above there's an error which says that there is no module named WebScraper. How can I deal with that problem?


回答1:


In the Spyder IDE, as I can tell from your screenshot, the current working directory (displayed in the top right corner) is different from the directory in which your script resides (displayed on top of the Editor panel).

If you open the "Tools" menu, select "Preferences", and switch to the "Run" tab, you will find a box named "Working Directory settings" where you can choose between "the directory of the file being executed" or "the current working directory". I suspect, as it is, you have selected the latter. Which would explain why the module cannot be found.

With the default setting — "the directory of the file being executed" — Spyder would simply execute the script in its own folder, and the script would have no problem finding the module.




回答2:


you are using spyder.

all you need to do is in spyder file explorer go to your project ie

/User/david/Document/Python/Project/

and then close the ipython terminal and start a new on (after you went to project folder) in the file explorer.

why your method not working, because ipython took the python execution path as current path opened in the file explorer (spyder)

run the code , it will work

other wise you need to provide relative path and use

 from . import WebScraper 
 x=WebScrapper().function



回答3:


By default, most of the apps have their default working directory.

Ex: If you will open command prompt, it's prompt is something like C:\Users\<username> in Windows, /Users/<username> in MAC.

So definitely, Spyder will also have its own working directory. Whenever you will execute any script, Spyder will try to look in that first.

My suggestion is to programatically check the working directory and navigate to the correct place (if we are in wrong place). Have a look at the below code.

import os
os.getcwd() # Check current directory's path
os.chdir('/Users/david/Documents/Python/Project') # Navigate

And after this try to import, it will work.

And if you wish, you can append this path to sys.path list.



来源:https://stackoverflow.com/questions/56813699/cannot-import-my-own-module-when-running-script-in-spyder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!