python - 将命令行参数传递给 runpy

标签 python python-3.x

如何将命令行 arge 传递给 runpy。

即如果我能做到 python3 -m foo --arg1=abc

如何在启动进程时将 --arg1=abc 添加为 sys.argv[1]:

import runpy
runpy.run_module('foo')

请注意,此处存在关于此主题的问题:pass command-line arguments to runpy但作者正在尝试做其他事情,但从未得到答复。

最佳答案

使用标准 python 库:argrparse

为了举例,我对 runpy 类进行了静态编码

from argparse import ArgumentParser as ArgParser

class runpy:
    @staticmethod
    def run_module(arg):
        print(arg)

if __name__ == '__main__':
    description = (
            'runpy commandline args')
    parser = ArgParser(description=description)
    parser.add_argument('--arg1', default="foo", type=str,
                            help='help text')
    options = parser.parse_args()
    runpy.run_module(options.arg1)

关于python - 将命令行参数传递给 runpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62750605/

相关文章:

python - 运行代码时在 Pycharm 中找不到目录

python - Pandas:读取 CSV 时强制错误

python - 如何在 cython 中获取类型化内存 View 的大小

python - 我可以用特定的数据集替换 'make_blobs' 吗?

python - 创建以键作为变量名的 Python 字典的简写

具有连续无界输入的Python ThreadPoolExecutor

Python Elasticsearch : BulkIndexError: 'not_x_content_exception' while trying to use helpers. 批量

python - word_tokenize TypeError : expected string or buffer

Python - 通过同时串联合并两个列表

python - 我在 pyqt5 中遇到错误,同时连接按钮