如何在python中加载带参数的python模块?

时间:2016-12-16 18:27:37

标签: python module python-module argv

我想创建一个用python -m mymodule somefile.py some_arg some_arg调用的python模块。

我的想法是,我可以设置别名alias="python -m mymodule"并通常使用python somefile.py some_arg some_arg调用文件。

在文件mymodule/__main__.py中,加载somefile.py并将其传递给参数列表的最佳方法是什么?

  • 我正在寻找一个通用的解决方案,即python2和3兼容。
  • 尽可能少侵入会很棒。如果somefile.py引发异常,则在追溯中几乎看不到mymodule
  • 这个模块的功能在这里并不详细,但是它设置了一些python内容(traceback hooks等),所以somefile.py应该在同一个进程中运行pythonicly。 os.systemsubprocess.Popen不合适。

2 个答案:

答案 0 :(得分:1)

好的,我发现了一些对python 3.5有用的东西,并且对python 2.7足够满意。

MyModule的/ 主要的.py

import sys

# The following block of code removes the part of 
# the traceback related to this very module, and runpy
# Negative limit support came with python 3.5, so it will not work
# with previous versions.
# https://docs.python.org/3.5/library/traceback.html#traceback.print_tb
def myexcepthook(type, value, tb):
     nb_noise_lines = 3
     traceback_size = len(traceback.extract_tb(tb))
     traceback.print_tb(tb, nb_noise_lines - traceback_size)
if sys.version_info >= (3, 5):
    sys.excepthook = myexcepthook

if len(sys.argv) > 1:
    file = sys.argv[1]
    sys.argv = sys.argv[1:]

    with open(file) as f:
         code = compile(f.read(), file, 'exec')
         exec(code)

somefile.py

import sys
print sys.argv
raise Exception()

在终端

$ python3 -m mymodule somefile.py some_arg some_arg
['somefile.py', 'some_arg', 'some_arg']
Traceback (most recent call last):
  File "somefile.py", line 3, in <module>
    raise Exception()

$ python2 -m mymodule somefile.py some_arg some_arg
['somefile.py', 'some_arg', 'some_arg']
Traceback (most recent call last):
  File "/usr/lib64/python3.5/runpy.py", line 184, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib64/python3.5/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/azmeuk/dev/testpy/mymodule/__main__.py", line 16, in <module>
    exec(code)
  File "somefile.py", line 3, in <module>
    raise Exception()

$ python somefile.py some_arg some_arg
['somefile.py', 'some_arg', 'some_arg']
Traceback (most recent call last):
  File "somefile.py", line 3, in <module>
    raise Exception()
Exception

但是,如果有人有更好的主张,那就太棒了!

答案 1 :(得分:1)

我认为limit的负值在python 3.5之前的跟踪模块中不起作用。这是一个与python 2.7一起使用的丑陋黑客

import sys
import traceback

class ExcFile(object):
    def __init__(self, file):
        self.topline = True
        self.file = file

    def write(self, s):
        if self.topline:
            u, s = s.split('\n', 1)
            self.file.write(u +'\n')
            self.topline = False
        if '#---\n' in s:
            u, s = s.split('#---\n', 1)
            self.file.write(s)
            self.write = self.file.write

ExcFile._instance = ExcFile(sys.stdout)    
# The following block of code removes the part of 
# the traceback related to this very module, and runpy
def myexcepthook(type, value, tb):
    traceback.print_exception(type, value, tb, file=ExcFile._instance)
sys.excepthook = myexcepthook

if len(sys.argv) > 1:
    file = sys.argv[1]
    sys.argv = sys.argv[1:]

    with open(file) as f:
        code = compile(f.read(), file, 'exec')
        exec(code) #---

所有这些都应该写在一个单独的文件中,以避免混乱__main__.py