Python 踩坑学习
【摘要】 Python 学习中遇到的坑,后续持续更新中。
1、VsCode Debug 配置文件
- 配置当前路径、命令行参数
"configurations": [
{
"name": "Python: 当前文件",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"args": [
"--data", "./data/",
"--output", "./output/",
"--lang", "en"],
"cwd": "${fileDirname}"
}
]
- 设置当前目录为工作目录
PYTHONPATH=$(pwd) python testing/main.py
- 输出重定向编码错误问题
env PYTHONIOENCODING=utf-8 python utils.py > log
# windows 在 git客户端执行脚本
2、生成requirements.txt
python -m pip install pipreqs
pipreqs ./ --encoding=utf-8
3、函数参数里的单星号、双星号
函数形参(压缩)
- 单星号(*):*agrs,将所以参数以元组(tuple)的形式导入
- 双星号(**):**kwargs,将参数以字典(dict)的形式导入
def foo(param1, *param2):
print(param1)
print(param2)
print(param2[2])
foo(1, 2, 3, 4, 5)
def bar(param1, **param2):
print(param1)
print(param2)
print(param2["a"])
bar(1, a=2, b=3)
"""
输出:
1
(2, 3, 4, 5)
4
1
{'a': 2, 'b': 3}
2
"""
函数实参(解压)
def test(a, b, c):
print(a, b, c)
args1 = (1,'2',[3])
test(*args1)
args2 = {'b': '2', 'c': [3], 'a': 1}
test(**args2)
"""
输出:
1 2 [3]
1 2 [3]
"""
4、list, np.array, torch.tensor 相互转换
ndarray = np.array(list) # list 转 numpy数组
list = ndarray.tolist() # numpy 转 list
tensor=torch.Tensor(list) # list 转 torch.Tensor
list = tensor.numpy().tolist() # torch.Tensor 转 list 先转numpy,后转list
ndarray = tensor.cpu().numpy() # torch.Tensor 转 numpy *gpu上的tensor不能直接转为numpy
tensor = torch.from_numpy(ndarray) # numpy 转 torch.Tensor
5、np.array, torch.tensor 数组嵌套
import numpy as np
a = [1, 2, 3]
b = [0, 1, 0]
a = np.array(a)
b = np.array(b)
c = a[b]
print(c)
# 输出:[1 2 1]
import torch
a = [1, 2, 3]
b = [0, 1, 0]
a = torch.Tensor(a)
b = torch.Tensor(b)
b = b.gt(0)
c = a[b]
print(c)
# 输出:tensor([2.])
6、Python 执行 shell
import os
import subprocess
x1 = os.system('pwd') # 直接输出shell结果,不会赋值给x1
print('x1', x1) # 打印结果:0, 表示命令执行成功
x2 = os.popen('pwd').read() # 不直接输出shell结果,会赋值给x2
print('x2', x2) # 打印结果:/home/zzk, os.popen() 返回的是一个【文件对象】
x3 = subprocess.call('pwd', shell=True) # 直接输出shell结果
print('x3', x3) # 打印结果:0
subprocess.call('echo 123', shell=True)
subprocess.call(['echo', '456'], shell=False)
x4 = subprocess.Popen('cd ../ && pwd', stdout=subprocess.PIPE, shell=True)
print('x4', x4.communicate()) # 打印结果
7、卸载所有三方包
pip list
pip freeze>python_modules.txt
pip uninstall -r python_modules.txt -y
8、保留小数
float(format(1.235,".2f"))
float('%.2f' % 1.235)
号外号外:想了解更多的AI技术干货,欢迎上华为云的AI专区,目前有AI编程Python等六大实战营供大家免费学习。
【版权声明】本文为华为云社区用户原创内容,未经允许不得转载,如需转载请发送邮件至:cloudbbs@huaweicloud.com;如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容。
- 点赞
- 收藏
- 关注作者
评论(0)