Mock command line arguments for Python script with `optparse`?

人盡茶涼 提交于 2019-12-12 13:34:01

问题


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

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?


回答1:


You can always assign a new list to 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.



来源:https://stackoverflow.com/questions/24000444/mock-command-line-arguments-for-python-script-with-optparse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!