python:停止导入模块解析命令行参数

python:停止导入模块解析命令行参数,python,argparse,Python,Argparse,我使用的是一个外部python模块,它不是由我编写的,因此无法更改。这个名为magnum()的模块处理所有可选的命令行参数。下面是一个示例来说明该行为: 脚本1.py #!/usr/bin/env python import magnum 执行脚本将产生: >>> ./script1.py -h [WARNING] - Python Imaging Library not found! [WARNING] - -> This means that the ImageSh

我使用的是一个外部python模块,它不是由我编写的,因此无法更改。这个名为magnum()的模块处理所有可选的命令行参数。下面是一个示例来说明该行为:

脚本1.py

#!/usr/bin/env python
import magnum
执行脚本将产生:

>>> ./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
现在我想写一个小脚本,它接受自己的命令行参数,然后使用magnum模块执行一些小计算。我想使用argparse来解析参数。但是,argparse的优先级似乎低于此外部模块的参数处理,并且无法识别我自己的参数:

脚本2.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
称之为:

>>>./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
无论我是在magnum之前还是之后导入argparse都没有关系。如果我不导入magnum,则argparse有效:

脚本3.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
#!/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
执行它会产生:

>>>./scrip2.py --x 3
3

我的问题是:在不编辑magnum的情况下,如何阻止magnum处理我的命令行参数?

虽然我认为没有任何“好”的解决方案,但您可以使用monkeypatch argparse使其成为nop:

class EmptyParser():
    def parse_args():
        return
    ... (more redirects for add_argument)
argparse.ArgumentParser = EmptyParser
import magnum
或者,您可以将导入magnum包装到一个函数中,通过该函数创建一个接口,并在magnum解析参数之前创建参数

def magnum(param1, param2):
    sys.argv = [param1, '--x', param2]
    import magnum

不过,这两种方法都非常粗糙

以下是基于上述评论/答案的工作解决方案,以供将来参考:

脚本3.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
#!/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
执行脚本表明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

此解决方案不会将任何参数转发给magnum,这正是我想要实现的。

查看github源代码

导入一个包(
magnum/\uuuuu init\uuuuu.py
)。
init
中的关键操作是

config.cfg.initialize(sys.argv)
它定义并创建一个
cfg=MagnumConfig()
。这检查了环境。它还定义并运行
optparse
解析器


因此,没有明显的方法绕过它的解析器,仍然设置计算环境。在导入magnum之前自行解析和调整sys.argv似乎是唯一的解决方案。

坦白地说,我认为你做不到。如果它试图在
import
上解析参数,那么它的架构似乎很差。argparse在import上什么都不做,这就是为什么顺序不重要的原因。在使用argparse(
parse_args
)后导入magnum,并将
sys.argv
设置为
[]
或magnum需要的任何东西。magnum看起来不像
magnum
是要导入的。它可能是可导入模块的脚本前端吗?不,它实际上是要导入的。至少他们所有的文档和例子都这么说。说明:
任何使用“import magnum”命令加载MicroMagnum的脚本都受以下命令行参数的约束:
。因此,此
导入
旨在设置计算环境。magnum可能不使用argparse(并且从错误消息判断,它不使用argparse)抱歉,之前的注释错误。更改sys.argv后导入magnum有效。