python能解决日常问题_【置顶】Python开发中常见问题

本文长期更新

可以通过CTRL+F在页面内进行问题关键字搜索

参考资料:

问题汇总:

如何在某.py文件中调用其他.py内的函数

解答:假设名为A.py的文件需要调用B.py文件内的C(x,y)函数

假如在同一目录下,则只需

import B

if __name__ == "__main__":

B.C(x,y)

若只需调用单个函数,也可以

from B import C

if __name__ == "__main__":

C(x,y)

若A.py和B.py位于不同的目录下,可以用以下方法

(假设B.py位于D盘的根目录下)

1.引用所在路径

import sys

sys.path.append('D:/')

import B

if __name__=="__main__":

print B.pr(x,y)

2.使用imp

import imp

B=imp.load_source('B','D:/B.py')

import B

if __name__=="__main__":

print B.pr(x,y)

注意:B.py这个文件的文件名不能以数字开头!

Python 中的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:\software\anaconda3\lib\site-packages\pip\basecommand.py", line 215, in main

status = self.run(options, args)

File "D:\software\anaconda3\lib\site-packages\pip\commands\install.py", line 335, in run

wb.build(autobuilding=True)

File "D:\software\anaconda3\lib\site-packages\pip\wheel.py", line 749, in build

self.requirement_set.prepare_files(self.finder)

File "D:\software\anaconda3\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files

ignore_dependencies=self.ignore_dependencies))

File "D:\software\anaconda3\lib\site-packages\pip\req\req_set.py", line 554, in _prepare_file

require_hashes

File "D:\software\anaconda3\lib\site-packages\pip\req\req_install.py", line 278, in populate_link

self.link = finder.find_requirement(self, upgrade)

File "D:\software\anaconda3\lib\site-packages\pip\index.py", line 465, in find_requirement

all_candidates = self.find_all_candidates(req.name)

File "D:\software\anaconda3\lib\site-packages\pip\index.py", line 423, in find_all_candidates

for page in self._get_pages(url_locations, project_name):

File "D:\software\anaconda3\lib\site-packages\pip\index.py", line 568, in _get_pages

page = self._get_page(location)

File "D:\software\anaconda3\lib\site-packages\pip\index.py", line 683, in _get_page

return HTMLPage.get_page(link, session=self.session)

File "D:\software\anaconda3\lib\site-packages\pip\index.py", line 811, in get_page

inst = cls(resp.content, resp.url, resp.headers)

File "D:\software\anaconda3\lib\site-packages\pip\index.py", line 731, in __init__

namespaceHTMLElements=False,

TypeError: parse() got an unexpected keyword argument 'transport_encoding'

解决方法:

执行conda install pip

报错:ImportError: No module named 'matplotlib.pyplot'; 'matplotlib' is not a package

解决方法:

检查*.py文件的文件名,我把文件名写成了matplotlib.py,改成matplotlib_test.py就好了

运行jupyter notebook报错:

Bad config encountered during initialization:The Jupyter HTML Notebook.

No such notebook dir: 'C:\Users\cb4\Documents\python'

解决办法:

Windows用户在C:\Users\\.jupyter, Linux用户在~\.jupyter路径下打开jupyter_notebook_config.py文件,找到c.NotebookApp.notebook_dir条目,修改路径。

报错:IndentationError: unindent does not match any outer indentation level

解决办法:一般是因为缩进时TAB和空格混用了,建议把TAB改为空格

问题:在github上打开**.ipynb文件过慢

解决办法:通过http://nbviewer.jupyter.org这个网站打开github的*.ipynb文件,在https://nbviewer.jupyter.org/github后加入对应*.ipynb文件的路径,如https://github.com/bermanmaxim/LovaszSoftmax/blob/master/demo_multiclass.ipynb的路径就是/bermanmaxim/LovaszSoftmax/blob/master/demo_multiclass.ipynb,那么在浏览器输入https://nbviewer.jupyter.org/github/bermanmaxim/LovaszSoftmax/blob/master/demo_multiclass.ipynb就可以了。

问题:__doc__是什么含义

解答:print(__doc__)将输出本文件头部的注释信息,如

# coding=utf-8

# import xxxlib

"""

测试p当前文件的__doc__,输出显示本段文字

"""

print(__doc__) #输出“测试p当前文件的__doc__”

print(xxxlib.__doc__) #输出xxxlib这个库的文档注释

问题:如何遍历指定目录及其子目录下所有文件

解答看下面代码

import os

def find_dir(dir_name="/data/测试图片/"):

"""

将file_path下的所有jpg文件的绝对路径存储到list

"""

print(find_dir.__doc__) #输出函数doc

file_list=[]

# 使用os.work(),path_name是当前目录,dir_list是当前目录下的所有目录名称,file_name是当前目录下的所有文件名称

for path_name, dir_list, files_name in os.walk(dir_name):

for file in files_name:

if os.path.splitext(file)[1]=='.jpg':

file_list.append(path_name+'/'+file)

for dir_name in dir_list:

find_dir(path_name+'/'+dir_name)

return file_list #将所有文件的绝对路径存储在file_list[]中返回

问题:中文字符读取问题(gbk,utf-8,unicode),dicom文件用pydicom读取获得变量age(python3显示是str类型,但是不知道编码类型),现在需要知道age中是否包含哪些中文字符

将age重新存储到一个字节数组中,以gbk格式存储,再编码转成unicode,这样操作unicode的字符就没问题了

def Trans2Unicode(str):

c=bytearray() # 字节数组c

for ch in str:

c.append(ord(ch)) # 存成gbk

print(type(c))

return c.decode('gbk') # 将gbk转成unicode

问题:python安装opencv后执行import cv2报错:ImportError: DLL load failed: 找不到指定的模块”

解决方案1:conda install --channel https://conda.anaconda.org/menpo opencv3

解决方案2:从https://pypi.tuna.tsinghua.edu.cn/simple/opencv-python/下载对应python版本的包,我是一个个试的,python3.6应该使用opencv_python-3.4.1.15-cp36-cp36m-win_amd64.whl

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值