Mock command line arguments for Python script with `optparse`?
Asked Answered
K

1

5

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?

Kirmess answered 2/6, 2014 at 17:52 Comment(1)
Why don't you run it via subprocess.call?Externalize
P
17

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.

Portsmouth answered 2/6, 2014 at 17:56 Comment(1)
This answer is helpful. Just a small improvement: import os sys.argv = [os.path.basename(__file__),, '-iq', '-q', directory]Fray

© 2022 - 2024 — McMap. All rights reserved.