python - 从另一个 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
解决方案
为什么不使用将 args 脚本导入原始脚本
import script_with_args
然后你可以在 script_with_args 中调用一个函数
让我们使用这个例子......如果以下两个脚本都位于同一个文件夹中
- 数学脚本.py
- 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
这样,您可以轻松地返回调用结果,并更改您在函数调用中为脚本提供的参数。
此外,为了完成这项工作,您需要确保您的脚本位于同一文件夹中。如果不是,您可以通过其他方式导入它们。
推荐阅读
- node.js - “偏移量”的值超出范围。它必须 >= 0 && <= 17825792
- javascript - 记录之间的差异
和 {}? - sql - 在 PostgreSQL 中搜索句子的确切部分
- java - 如何在 mockito 中模拟一个函数?
- javascript - 在 Javascript 上保存处理程序之前 vTiger 字段上的字符串连接(内部代码)
- mysql - 请问如何将sql查询转换为laravel查询
- r - 沿数据框行滑动并将行与下一行进行比较
- sql - 从 SQL 中提取表会导致出现此错误:ERROR 180-322: Statement is not valid or it is used out of proper order
- javascript - WebStorm 缓存数据有问题吗?
- reactjs - 启动时反应本机副驾驶无限重新渲染