简体   繁体   English

使用`optparse`模拟Python脚本的命令行参数?

[英]Mock command line arguments for Python script with `optparse`?

A Python script that I want to use (called snakefood ) is normally run from the commandline and takes commandline arguments, eg: 我想要使​​用的Python脚本(称为snakefood )通常从命令行运行并接受命令行参数,例如:

sfood /path/to/my/project

The parsing of the commandline arguments happens in a file called gendeps.py using optparse . 使用optparse在名为gendeps.py的文件中解析命令行参数。 However, I want to use the snakefood module from another script. 但是,我想从另一个脚本中使用snakefood模块。 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? 有没有办法我可以以某种方式模拟命令行参数传递给snakefood或重写gendeps.py的方式,以便它不再依赖于optparse

You can always assign a new list to sys.argv : 您始终可以为sys.argv分配新列表:

import sys

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

optparse uses sys.argv[1:] as input when no explicit arguments have been passed in. 当没有传入显式参数时, optparse使用sys.argv[1:]作为输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM