简体   繁体   English

Python:将参数从argparse传递到导入的脚本

[英]Python: Pass arguments from argparse to imported scripts

I'm building a command line tool which executes some python-scripts (k2_fig1 - k2_fig3) in one main *.py-file (let's call it "main_file.py"). 我正在构建一个命令行工具,该工具在一个主要* .py文件中执行一些python脚本(k2_fig1-k2_fig3)(我们将其称为“ main_file.py”)。 In this "main_file.py" the user has to fill in some parameters for the database connection (username, dbname, etc.) 用户必须在此“ main_file.py”中填写一些数据库连接参数(用户名,dbname等)。
Now I don't know how to pass these parameters to every single python-script I am importing. 现在,我不知道如何将这些参数传递给我要导入的每个python脚本。 What do I have to code to these imported files? 我必须对这些导入的文件进行编码吗?
This is my code of the "main_file.py": 这是我的“ main_file.py”代码:

import argparse
def main():
  parser = argparse.ArgumentParser()

  parser.add_argument('-D', '--database', action="store", type=str, dest="my_dbname",  required=True, help="DB name")

  parser.add_argument('-U', '--username', action="store", type=str, dest="my_username", required=True, help="DB username")

  args = parser.parse_args()


  # Import different scripts
  import k2_fig1
  import k2_fig2
  import k2_fig3

if __name__ == '__main__':
  main()

Without knowing anything else about k2fig_1 et al., you'll need to call them using subprocess rather than importing them. 在不了解k2fig_1等其他信息的情况下,您将需要使用subprocess进程来调用它们,而不是导入它们。

import argparse
import subprocess

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('-D', '--database', action="store", type=str, dest="my_dbname",  required=True, help="DB name")
  parser.add_argument('-U', '--username', action="store", type=str, dest="my_username", required=True, help="DB username")

  args = parser.parse_args()
  for script in ['k2_fig1', 'k2_fig2', 'k2_fig3']:
      subprocess.call([script, '-U', args.my_username, '-D', args.my_dbname])

if __name__ == '__main__':
  main()

I think the best way is to copy the namespace attributes to a "config" module:: 我认为最好的方法是将名称空间属性复制到“ config”模块中:

import argparse

from . import config
from . import other

def update_obj(dst, src):
    for key, value in src.items():
        setattr(dst, key, value)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-D', '--database')
    parser.add_argument('-U', '--username')

    args = parser.parse_args('-D foo'.split())

    update_obj(config, args)

And the "other module":: 和“其他模块”:

from . import config

def some_func():
    assert config.database == 'foo'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM