【置顶】Python开发中常见问题参考资料:问题汇总:
本文长期更新
可以通过CTRL+F
在页面内进行问题关键字搜索
if __name__ == '__main__'
该如何理解
Python不同于C++等语言,它没有统一的程序入口, .py
文件是从第一行开始一行一行地执行。假设hub.py
文件的前半部分定义了一些函数,后半部分写了一些代码来调用上面的函数,如下所示:#文件上半部分定义函数 def A(): #函数A的实现 def B(): #函数B的实现 #文件下半部分调用函数并输出一些信息 A() B() print("this message should not be shown out of this file")
如果我们在outside.py
文件中调用hub.py
时,就会打印出this message should not be shown out of this file
,如果不希望别的文件调用hub.py
时打印出上述信息,则可以将hub.py
改成:
#文件上半部分定义函数 def A(): #函数A的实现 def B(): #函数B的实现 #文件下半部分调用函数并输出一些信息 #但是别的文件调用hub.py时不打印this message should not be shown out of this file if __name__ == '__main__' #注意这句话 A() B() print("this message should not be shown out of this file")
这样,别的文件调用hub.py
时就不会打印出this message should not be shown out of this file
原因就是:
__name__
是内置变量,用于表示当前模块的名字,同时还能反映一个包的结构。__name__
值为 __main__
pip install keras
报错:TypeError: parse() got an unexpected keyword argument 'transport_encoding'
在执行pip install keras
时出错:Exception: Traceback (most recent call last): File "D:softwareanaconda3libsite-packagespipasecommand.py", line 215, in main status = self.run(options, args) File "D:softwareanaconda3libsite-packagespipcommandsinstall.py", line 335, in run wb.build(autobuilding=True) File "D:softwareanaconda3libsite-packagespipwheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "D:softwareanaconda3libsite-packagespip eq eq_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "D:softwareanaconda3libsite-packagespip eq eq_set.py", line 554, in _prepare_file require_hashes File "D:softwareanaconda3libsite-packagespip eq eq_install.py", line 278, in populate_link self.link = finder.find_requirement(self, upgrade) File "D:softwareanaconda3libsite-packagespipindex.py", line 465, in find_requirement all_candidates = self.find_all_candidates(req.name) File "D:softwareanaconda3libsite-packagespipindex.py", line 423, in find_all_candidates for page in self._get_pages(url_locations, project_name): File "D:softwareanaconda3libsite-packagespipindex.py", line 568, in _get_pages page = self._get_page(location) File "D:softwareanaconda3libsite-packagespipindex.py", line 683, in _get_page return HTMLPage.get_page(link, session=self.session) File "D:softwareanaconda3libsite-packagespipindex.py", line 811, in get_page inst = cls(resp.content, resp.url, resp.headers) File "D:softwareanaconda3libsite-packagespipindex.py", line 731, in __init__ namespaceHTMLElements=False, TypeError: parse() got an unexpected keyword argument 'transport_encoding'
解决方法:
执行conda install pip
*.py
文件的文件名,我把文件名写成了matplotlib.py
,改成matplotlib_test.py
就好了jupyter notebook
报错:
Bad config encountered during initialization:The Jupyter HTML Notebook.
No such notebook dir: 'C:Userscb4Documentspython'