首页 > 解决方案 > 从另一个 python 脚本调用带有 args 的 python 脚本?

问题描述

python的新手。我正在尝试使用另一个 python 脚本中的 args 调用 python 脚本。

Python 脚本script_with_args.py (带参数):

python script_with_args.py a1 b1 c1 d1

print('Number of arguments:', len (sys.argv), 'arguments.')

print('Argument List:', str(sys.argv))

Python 脚本 - 2:(调用 python 脚本 - script_with_args.py

python script2.py

#call`script_with_args.py` 

我正在尝试调用script_with_args.py来自脚本 2 -script_with_args.py ab bc ca

标签: python

解决方案


为什么不使用将 args 脚本导入原始脚本

import script_with_args

然后你可以在 script_with_args 中调用一个函数

让我们使用这个例子......如果以下两个脚本都位于同一个文件夹中

  1. 数学脚本.py
  2. main_script.py

数学脚本将包含一些我们想从主脚本调用的函数,例如加法和减法。

所以我们的 main_script 看起来像......

## This is main_script.py
import math_script                        #This will import our script so we can call its functions

numberOne = 2
numberTwo = 3
numberThree = 5
result1 = math_script.add_two(numberOne, numberTwo)
print('The result is:', result1)
result2 = math_script.add_three(numberOne, numberTwo, numberThree)
print('The result is:', result2)

我们的 math_script.py 看起来像……

## This is math_script.py
def add_two(arg1, arg2):
    result = arg1 + arg2
    print('Adding two numbers...')
    return result

def add_three(arg1, arg2, arg3):
    return arg1 + arg2 + arg3

这样,您可以轻松地返回调用结果,并更改您在函数调用中为脚本提供的参数。

此外,为了完成这项工作,您需要确保您的脚本位于同一文件夹中。如果不是,您可以通过其他方式导入它们。


推荐阅读