首页 > 解决方案 > 使用不同的变量运行 python 命令?

问题描述

我想用不同的变量执行 python 脚本。我必须从文件夹中批处理图像文件,但我只想从具有不同变量的脚本中执行。喜欢

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18. 19, 20]

!python autozoom.py --in ./images/1.jpg --out ./videos/1.mp4
!python autozoom.py --in ./images/2.jpg --out ./videos/2.mp4
!python autozoom.py --in ./images/3.jpg --out ./videos/3.mp4
!python autozoom.py --in ./images/4.jpg --out ./videos/4.mp4

等到20

对不起,我是python语言的绝对初学者。任何答案或建议我都会非常感激!:) 谢谢

标签: python

解决方案


让我们谈谈如何autozoom.py最好地编写来支持这种用例,而不需要在 20 次不同的时间启动新的 Python 解释器。在理想的世界中,它可能如下所示:

import argparse

def convert(infile, outfile):
    pass # do the magic here

def main():
    ap = argparse.ArgumentParser
    ap.add_argument('--in', dest='infile', type=argparse.FileType('rb'))
    ap.add_argument('--out', dest='outfile', type=argparse.FileType('wb'))
    args = ap.parse_args()
    convert(args.infile, args.outfile)

if __name__ == '__main__':
  main()

...命令行解析代码调用执行实际工作的函数,但也可以直接调用该函数。

如果是这种情况,您使用该convert函数的代码可能如下所示:

import autozoom

for i in range(1, 21):
    with open(f'images/{i}.jpg', 'rb') as input_file, \
         open(f'videos/{i}.mp4', 'wb') as output_file:
        autozoom.convert(input_file, output_file)

推荐阅读