繁体   English   中英

使用来自另一个 python 脚本的 args 调用 python 脚本?

[英]Call python script with args from another python script?

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

Python 脚本script_with_args.py (带 args):

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` 

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

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

import script_with_args

然后您可以在 script_with_args 中调用 function

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

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

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

所以我们的 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

这样,您可以轻松返回调用结果并更改 arguments 您在 function 调用中提供的脚本。

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

暂无
暂无

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

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