【问题标题】:how to pass arguments to imported script in Python如何在 Python 中将参数传递给导入的脚本
【发布时间】:2014-08-01 22:12:18
【问题描述】:

我有一个如下形式的脚本 (script1.py):

#!/bin/python

import sys

def main():
    print("number of command line options: {numberOfOptions}".format(numberOfOptions = len(sys.argv)))
    print("list object of all command line options: {listOfOptions}".format(listOfOptions = sys.argv))
    for i in range(0, len(sys.argv)):
        print("option {i}: {option}".format(i = i, option = sys.argv[i]))

if __name__ == '__main__':
    main()

我想将此脚本导入另一个脚本 (script2.py) 并传递给它一些参数。脚本script2.py 可能如下所示:

import script1

listOfOptions = ['option1', 'option2']
#script1.main(listOfOptions) insert magic here

如何将script2.py 中定义的参数传递给script1.py 的主函数,就好像它们是命令行选项一样?

那么,例如,执行以下操作是否符合 Python 风格?:

import script1
import sys

sys.argv = ['option1', 'option2']
script1.main()

【问题讨论】:

标签: python command-line import arguments options


【解决方案1】:

单独的命令行解析和调用函数

为了代码的可重用性,将执行函数与命令行解析分开是很实用的

scrmodule.py

def fun(a, b):
    # possibly do something here
    return a + b

def main():
    #process command line argumens
    a = 1 #will be read from command line
    b = 2 #will be read from command line
    # call fun()
    res = fun(a, b)
    print "a", a
    print "b", b
    print "result is", res

if __name__ == "__main__":
    main()

从其他地方重复使用它

from scrmodule import fun

print "1 + 2 = ", fun(1, 2)

【讨论】:

  • 非常感谢。这是非常好的建议。不幸的是,script1.py,包含函数main()中的主要处理,代表了一些我无法更改的遗留代码。
  • @d3pd - 现在我明白了。您将值设置为 sys.argv 的方法看起来不错。如果您无法修改旧脚本,这可能是一种方法。
【解决方案2】:
# script1.py
#!/bin/python

import sys

#main function is expecting argument from test_passing_arg_to_module.py code.
def main(my_passing_arg):
    print("number of command line options:  {numberOfOptions}".format(numberOfOptions = len(sys.argv)))
    print("list object of all command line options: {listOfOptions}".format(listOfOptions = my_passing_arg))
    print(my_passing_arg)
if __name__ == '__main__':
    main()

#test_passing_arg_to_module.py
import script1
my_passing_arg="Hello world"
#calling main() function from script1.py code.
#pass my_passinga_arg variable to main(my_passing_arg) function in scritp1.py. 
script1.main(my_passing_arg)
##################
# Execute script
# $python3.7 test_passing_arg_to_module.py
# Results.
# number of command line options:  1
# list object of all command line options: Hello world
# Hello world


【讨论】:

  • 这个答案没有解释它为什么起作用,如何从中学习?另外,您已将解释器代码与文件代码合并,请编辑您的帖子和说明
猜你喜欢
  • 2019-06-11
  • 2023-03-14
  • 1970-01-01
  • 2010-10-26
  • 2020-05-11
  • 1970-01-01
  • 1970-01-01
  • 2012-08-23
  • 1970-01-01
相关资源
最近更新 更多