本文介绍了用`optparse`模拟Python脚本的命令行参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使用的Python脚本(称为 snakefood )通常从命令行运行,并接受命令行参数,例如:

A Python script that I want to use (called snakefood) is normally run from the commandline and takes commandline arguments, eg:

sfood /path/to/my/project

命令行参数的解析发生在名为 gendeps.py 使用optparse.但是,我想使用另一个脚本中的snakefood模块.有什么方法可以模拟将命令行参数传递给snakefood或重写gendeps.py以便不再依赖optparse吗?

The parsing of the commandline arguments happens in a file called gendeps.py using optparse. However, I want to use the snakefood module from another script. Is there a way I can somehow mock the passing of commandline arguments to snakefood or a way of rewriting gendeps.py so that it doesn't depend on optparse anymore?

推荐答案

您始终可以将新列表分配给sys.argv:

You can always assign a new list to sys.argv:

import sys

sys.argv = ['programname', '-iq', '-q', directory]
gendeps.gendeps()

当未传递任何显式参数时,

optparse使用sys.argv[1:]作为输入.

optparse uses sys.argv[1:] as input when no explicit arguments have been passed in.

这篇关于用`optparse`模拟Python脚本的命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-15 22:29