0%

argparse

python argparse模块

argparse是预先在下图位置输入参数,比如图片旋转的角度,图片的长宽还有图片最终存放的位置。然后运行此程序后,这些参数就自动的被调用了。

20


以下为网上找的相关资料:

vars()
如果对象具有dict属性,则vars()函数返回给定对象的dict属性.(函数返回对象object的属性和属性值的字典对象1 )

日常运用:
将args传递的参数从namespace 转换为dict,这样就不用将args包含的参数一一列举出来再传入相应函数中,化简代码,增加可读性.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class WGAN():
def __init__(self,d1,d2):
self.args = d1
self.kwargs = d2


def printval(self):
print(self.args)
print(self.kwargs)

def parse_train():
parser = argparse.ArgumentParser(description="Tain WGAN model")
parser.add_argument('--try1',dest='d1',default=1, type = int, help = "this is try1")
parser.add_argument('--try2',dest='d2',default=2, type = int, help = "this is try2")
args = parser.parse_args()
return args

def main():
args = parse_train()
wgan = WGAN(**vars(args))
wgan.printval()

if __name__ == "__main__":
main()

例如上述代码,vars就是将argparse中的所有属性都传给wgan。

若不用 wgan = WGAN(**vars(args)),则需要输入wgan = WGAN(args.d1,args.d2),在参数较多的情况下十分冗余,不便阅读


Python os.path() 模块

os.path 模块主要用于获取文件的属性。

以下是 os.path 模块的几种常用方法:

方法 说明
os.path.abspath(path) 返回绝对路径
os.path.basename(path) 返回文件名
os.path.isdir(path) 判断路径是否为目录
os.path.dirname(path) 返回文件路径
os.path.exists(path) 如果路径 path 存在,返回 True;如果路径 path 不存在,返回 False。
os.path.lexists 路径存在则返回True,路径损坏也返回True
os.path.expanduser(path) 把path中包含的”“和”user”转换成用户目录
os.path.isabs(path) 判断是否为绝对路径
os.path.join(path1[, path2[, …]]) 把目录和文件名合成一个路径
1
2
3
4
5
import os
file='/t/a.txt'
print(os.path.basename(file) ) # 返回文件名
print(os.path.dirname(file) ) # 返回目录路径
print(os.path.abspath(file) )

TIM图片20200226010748

1
2
3
4
5
6
7
8
9
10
import os

Path1 = 'home'
Path2 = 'develop'
Path3 = 'code'

Path10 = Path1 + Path2 + Path3
Path20 = os.path.join(Path1,Path2,Path3)
print ('Path10 = ',Path10)
print ('Path20 = ',Path20)
1
2
3
**输出**
Path10 = homedevelopcode
Path20 = home\develop\code

shutil

shutil.rmtree() 表示递归删除文件夹下的所有子文件夹和子文件。