【发布时间】:2016-09-30 03:14:06
【问题描述】:
我有一个 script_A,它使用 argparser 处理不同的输入,我用它来执行一个函数。我现在需要脚本 B 来调用并让所有脚本 A 从内部运行(让它处理不同的输入)。我正在使用 Windows。
目标: Script_B 将根据 script_A 的输出做进一步的分析。 Script_A 的行为根据传递的参数选项而改变。 Script_B 的行为始终相同。我宁愿不要把 script_A 和 script_B 组合成一个庞大的脚本。
目标已更新:为了让 script_B 正常工作,我需要运行 script_A,然后传递其中一个字典,即字典 D,它被计算(从 A 输出)传递给B. 直到所有 script_A 运行后才计算字典。
这就是 Script_A 的样子
import sys
import os
from argparse import ArgumentParser
def function 1:
#it does stuff....
def function 2:
#it does other stuf...
if __name__ == "__main__":
parser = ArgumentParser(description = "functionA.py -i [--print]
parser.add_argument('-i', '--id', help="Please write A or B", required=True)
parser.add_argument('-r', '--re', help="Please write C or D, required=True)
sysargs = parser.parse_args()
#Variable definitions
if str(sysargs.id) == "A":
#Uses file A located in directory X to perform analysis
#calls function A to perform analysis
elif str(sysargs.id) == "B":
#Uses file B located in Directory Y to perform analysis
#calls function B to perform analysis
if str(sysargs.re) == "C"
#Provides thorough printout of analysis (more in depth for debugging)
if str(sysargs.re) == "D"
#Does Nothing (no debugging option)
脚本 A 运行良好,当我使用它时它就完成了它的工作。我使用命令行参数提交输入,这是必需的,有时是可选的。
这就是脚本B,我试过以下:
1
import sys
import numpy as np
import os
import script_A
os.system("script_A.py", -i "A" -r "C")
#Other stuff that script B does
2
import sys
import os
import script_A
exec(script_A.py[-i "A" -r "C"])
#Other stuff that script B does
3
import os
import sys
from subprocess import call
subprocess.call("script_A.py", -i "A" -r "C")
#Other stuff that script B does
我看过这里:Calling an external command in Python
这里:importing a python script from another script and running it with arguments
但无法从他们所说的内容中弄清楚。任何帮助是极大的赞赏。我还是 Python 的初学者。
我基于 cmets 尝试了以下方法:
1
import subprocess
import script_A
p.subprocess.Popen("script_A.py", "-i", "A", "-r", "none", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(stdoutput, erroutput) = p.communicate()
TypeError: __init_() 为关键字参数“stdout”获取了多个值
我尝试添加 self 参数,但出现以下错误
p.subprocess.Popen("script_A.py", "-i", "A", "-r", "C", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
TypeError: __init_() 为关键字参数“stderr”获得了多个值
2
import subprocess
import script_A
process= Popen(["script_A", "-i", "A", "-r", "C"], stdout = subprocess.PIPE, stderr=subprocess.STDOUT)
output = process.communicate()
OSError: [ERRno2] 没有这样的文件或目录
在执行子进程中转到 /subprocess.py 的目录出错
引发 child_exception
我不知道这是什么意思。
【问题讨论】:
-
为什么需要通过命令行传递参数?只需
import并直接调用函数。 -
抱歉,您能详细说明一下吗?只是为了澄清我不需要从脚本 B 中的脚本 A 运行单独的函数。我需要运行整个事情。我还想灵活地解析参数,以便在我想要显示更多输出时与何时不显示。
-
那么这些替代品做什么(或不做什么)?你期待发生什么?如果您不直接使用它的功能(如在
os.system版本中),则不需要import script_A。 -
在您使用
argparse时,您不需要str(sysargs.id)。args=parser.parse_args()和if args.id == 'A':...应该足够了。 -
哎呀,抱歉 hpaulj 我确实在脚本 A 中有 args = parser.parse_args()。让我现在添加它。它仍然不适用于该行。我将在下一次编辑中详细说明替代方案。谢谢
标签: python shell command-line argparse