[英]python: stop imported module from parsing command line arguments
I'm using an external python module, which is not written by me therefore cannot be changed. 我正在使用外部python模块,这不是我写的,因此无法更改。 This module, called magnum ( http://micromagnum.informatik.uni-hamburg.de ), processes all optional command line arguments. 该模块称为magnum( http://micromagnum.informatik.uni-hamburg.de ),处理所有可选的命令行参数。 Here an example to illustrate the behavior: 这里举例说明行为:
script1.py script1.py
#!/usr/bin/env python
import magnum
executing the script yields: 执行脚本产生:
>>> ./script1.py -h
[WARNING] - Python Imaging Library not found!
[WARNING] - -> This means that the ImageShapeCreator and related classes are not available!
[ INFO] - Imported FFTW wisdom from file
Usage: scipt1.py [options]
Options:
--version show program's version number and exit
-h, --help show this help message and exit
Hardware options:
Options that control which hardware is used.
-g GPU_ID enable GPU processing (using 32-bit accuracy) on cuda
device GPU_ID. The simulator will fall back to CPU
mode if it was not compiled with CUDA support or when
no CUDA capable graphics cards were detected.
-G GPU_ID enable GPU processing (using 64-bit accuracy) on cuda
device GPU_ID. TODO: Describe fallback behaviour.
-t NUM_THREADS, --threads=NUM_THREADS
enable CPU multithreading with NUM_THREADS (1..64)
threads. This parameter instructs the fftw library to
use NUM_THREADS threads for computing FFTs.
Logging options:
Options related to logging and benchmarking.
-l LEVEL, --loglevel=LEVEL
set log level (0:Debug, 1:Info, 2:Warn, 4:Error,
5:Critical), default is Debug (0).
--prof Log profiling info at program exit.
Parameter sweep options:
These options have only an effect when the simulation script uses a
Controller object to sweep through a parameter range.
-p RANGE, --param-range=RANGE
select parameter set to run, e.g. --param-range=0,64
to run sets 0 to 63.
--print-num-params print number of sweep parameters to stdout and exit.
--print-all-params print all sweep parameters to stdout and exit.
Miscellanous options:
--on_io_error=MODE Specifies what to do when an i/o error occurs when
writing an .omf/.vtk file. 0: Abort (default), 1:
Retry a few times, then abort, 2: Retry a few times,
then pause and ask for user intervention
Now I want to write a small script that takes its own command line arguments and then uses the magnum module to perform some small calculation. 现在我想写一个小脚本,它接受自己的命令行参数,然后使用magnum模块执行一些小的计算。 I would like to use argparse to parse the arguments. 我想用argparse来解析参数。 However, argparse seems to have a lower priority than the argument processing of this external module and my own arguments fail to be recognized: 但是,argparse的优先级似乎低于此外部模块的参数处理,并且我自己的参数无法识别:
script2.py script2.py
#!/usr/bin/env python
import argparse
import magnum
parser = argparse.ArgumentParser(
description='TEST')
parser.add_argument('--x',
help='test_arg')
args = parser.parse_args()
print args.x
Calling it: 打电话给:
>>>./scrip2.py --x 3
[WARNING] - Python Imaging Library not found!
[WARNING] - -> This means that the ImageShapeCreator and related classes are not available!
[ INFO] - Imported FFTW wisdom from file
Usage: test.py [options]
test.py: error: no such option: --x
It does not matter if I import argparse before or after magnum. 如果我在magnum之前或之后导入argparse并不重要。 The argparse works if I don'f import magnum: 如果我不输入大量的话,argparse会起作用:
script3.py script3.py
#!/usr/bin/env python
import argparse
parser = argparse.ArgumentParser(
description='TEST')
parser.add_argument('--x',
help='test_arg')
args = parser.parse_args()
print args.x
Executing it yields: 执行它会产生:
>>>./scrip2.py --x 3
3
My question is: How can I stop magnum from processing my command line arguments, without editing magnum? 我的问题是:如何在不编辑马格南的情况下停止处理我的命令行参数?
While I don't think there are any 'good' solutions, you can monkeypatch argparse to make it nop: 虽然我认为没有任何“好”的解决方案,但你可以使用monkeypatch argparse使它成为nop:
class EmptyParser():
def parse_args():
return
... (more redirects for add_argument)
argparse.ArgumentParser = EmptyParser
import magnum
Alternatively, you can wrap importing magnum in a function and create an interface to it through that function and creating arguments before magnum parses them. 或者,您可以在函数中包装导入magnum,并通过该函数创建一个接口,并在magnum解析它们之前创建参数。
def magnum(param1, param2):
sys.argv = [param1, '--x', param2]
import magnum
Both approaches are super hacky, though. 不过,这两种方法都是超级黑客。
Looking at the github source, https://github.com/MicroMagnum 查看github源代码, https://github.com/MicroMagnum
import magnum
imports a package ( magnum/__init__.py
). 导入包( magnum/__init__.py
)。 And the key action in the init
is 而init
的关键操作是
config.cfg.initialize(sys.argv)
That defines and creates a cfg = MagnumConfig()
. 这定义并创建了一个cfg = MagnumConfig()
。 That checks the environment. 检查环境。 It also defines and runs an optparse
parser. 它还定义并运行optparse
解析器。
So there's no obvious way of bypassing its parser and still setup the computing environment. 因此,没有明显的方法绕过其解析器并仍然设置计算环境。 Doing your own parsing and tweaking sys.argv
before import magnum
appears to be the only solution. 在import magnum
之前进行自己的解析和调整sys.argv
似乎是唯一的解决方案。
For future reference, here the working solution based on the comments / answers above: 为了将来参考,这里基于以上评论/答案的工作解决方案:
script3.py script3.py
#!/usr/bin/env python
import argparse
import sys
parser = argparse.ArgumentParser(
description='TEST')
parser.add_argument('--x',
help='test_arg')
args = parser.parse_args()
sys.argv = [sys.argv[0]]
import magnum
print args.x
Executing the script indicates that magnum is imported correctly but also that the arguments have been parsed and stored in the args variable: 执行脚本表明正确导入了magnum,但是参数已被解析并存储在args变量中:
>>>./script3.py --x 3
[WARNING] - Python Imaging Library not found!
[WARNING] - -> This means that the ImageShapeCreator and related classes are not available!
[ INFO] - Imported FFTW wisdom from file
[ INFO] - ----------------------------------------------------------------------
[ INFO] - MicroMagnum 0.2rc3
[ INFO] - Copyright (C) 2012 by the MicroMagnum team.
[ INFO] - This program comes with ABSOLUTELY NO WARRANTY.
[ INFO] - This is free software, and you are welcome to redistribute it under
[ INFO] - certain conditions; see the file COPYING in the distribution package.
[ INFO] - ----------------------------------------------------------------------
[ INFO] - FFTW using 1 threads from now on
[ INFO] - CUDA GPU support: no
3
This solution will not forward any arguments to magnum, which is what I wanted to achieve. 这个解决方案不会将任何参数转发给magnum,这是我想要实现的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.