如何在Python中将参数传递给导入的脚本

时间:2014-06-11 18:23:58

标签: python command-line import arguments options

我有以下格式的脚本(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的主函数,就好像它们是命令行选项一样?

因此,例如,Pythonic是否可以执行以下操作?:

import script1
import sys

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

2 个答案:

答案 0 :(得分:2)

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

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

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)

答案 1 :(得分:0)

# 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