【问题标题】:Python command line call to main does not go into main function对 main 的 Python 命令行调用不会进入 main 函数
【发布时间】:2020-11-23 23:02:32
【问题描述】:

我有一个具有以下主要功能的 python 文件:

if __name__ == '__main__':
    args = docopt(__doc__)

    print('source: %s' % args['--src'])
    print('target: %s' % args['--tgt'])

现在当我调用这个函数时:

python test.py --src file1 --tgt file2

我明白了:

Usage:
    test.py --src=<file> --tgt=<file>
Options:
    -h --help            Show this screen.
    --src=<file>         src
    --tgt=<file>         tgt

但是主函数逻辑只是没有被调用。如何解决这个问题?

我试过了:

python test.py --src=file1 --tgt=file2

但我得到了相同的结果。

【问题讨论】:

  • python test.py --src=file1 --tgt=file2
  • 是的,我试过了..同样的结果..
  • 您还可以从pdb 库中受益。一些放置良好的 pdb.set_trace() 调用将使您更容易确定代码的行为。如果您在 args= 调用之前放置一个,您会发现它确实输入了该 if 语句。
  • @Erich 谢谢,我把 set_trace 放在 args = docopt(doc) 的下面 .. 它进入 main 但之后的逻辑不会被调用..
  • 正在 被输入,否则 docopt 不会解析参数并产生使用消息。那么,您的文档字符串是什么

标签: python arguments python-3.6 main


【解决方案1】:

查看您的文档字符串。我认为问题是由于那里的UsageOptions 部分之间缺少换行符。

我试过这个文档字符串,效果很好:

"""
Usage:
    test.py --src=<file> --tgt=<file>

Options:
    -h --help       Show this screen.
    --src<file>     src
    --tgt=<file>    tgt
"""
from docopt import docopt

if __name__ == '__main__':
    args = docopt(__doc__)
    print('source: %s' % args['--src'])
    print('target: %s' % args['--tgt'])

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 2011-11-21
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 2014-04-02
    • 2020-02-13
    • 1970-01-01
    相关资源
    最近更新 更多