Python控制台参数传入方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hxcaifly/article/details/80623466

1. 前言

当把python文件作为独立的模块运行时,有时需要在执行Python文件的时候向其传入参数。那这些参数应该怎么传进去呢?文件本身需要做些什么处理呢?

2. 实际的应用场景

在做图像处理时,把图像的处理逻辑全部放在一个文件里。在执行这个文件时,需要传入输入图像的路径,已经输出图像的名称等参数。具体处理过程如下,保存的python文件名称为demo.py。

from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import load_img
import numpy as np
import argparse

#设置参数
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,help="path to the input image")
ap.add_argument("-o", "--output", required=True,help="path to output directory to store augmentation examples")
ap.add_argument("-p", "--prefix", type=str, default="image",help="output filename prefix")
args = vars(ap.parse_args())
#获取参数并且打印出来
print args['image']
print args['output']
#图像处理逻辑略

执行方式如下:

Python demo.py --image my.png --output out.png

猜你喜欢

转载自blog.csdn.net/hxcaifly/article/details/80623466
今日推荐