当前位置: 代码迷 >> python >> 从另一个python脚本调用面向命令行的脚本
  详细解决方案

从另一个python脚本调用面向命令行的脚本

热度:76   发布时间:2023-07-16 10:11:26.0

我使用的是用Python编写的脚本,它使用argparse模块从命令行获取它的参数。 我尝试尽可能少地修改此文件,因为各种人都在使用它。

例如:脚本名为CLscript.py,我用它来调用它

python CLscript.py -option1 arg1 -flag1 -option2 arg2

但我面临的情况是,我希望自动化更高级别的东西,并使用各种脚本生成的参数自动启动此脚本。

我想继续使用此脚本中现有的所有选项和标志组织。

例如,当我从topLevelScript.py运行CLscript.py时:

subprocess.call("python CLscript.py -option1 arg1 -flag1 -option2 arg2")

,我从输出中看到出现问题,我停止执行topLevelScript.py,但CLscript.py继续在另一个我必须手动杀死的python进程中独立运行。 我无法在调试模式下启动topLevelScript.py以在CLscript.py中的断点处停止。

我想从python内部完成所有这些操作,无需构建命令行字符串并使用子进程启动CLscript.py。 每个调用都将保持附加到同一个原始启动,就像函数调用一样,而不是像使用subprocess.call()那样创建多个python线程。

有点像是以某种方式向脚本传递带有选项,标志和参数的字符串列表吗?

有没有类似的东西

import CLscript.py
CLsimulator(CLscript,["-option1",arg1,"-flag1","-option2",arg2])

会这样的吗? 将大部分代码提取到一个新函数中,该函数需要与通过命令行发送的参数类似的参数。 然后编写一个新函数,收集命令行参数并将它们发送到第一个函数...

def main(foo, bar):
    a = foo + bar
    print a

def from_command_line():
    foo, bar = get_command_line_args()
    main(foo, bar)

if __name__ == "__main__":
    from_command_line()

然后你的其他脚本可以调用main函数。

首先,使用而不是subprocess.call()

import subprocess

child = subprocess.Popen(
    ['python', 'CLscript.py', '-option1', 'arg1', '-flag1', '-option2', 'arg2'],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE
)

请注意,作为第一个参数,您可以按照自己的意愿传递array of strings
其次,重定向标准文件描述符非常重要。 请参见 。
现在你有了一个child变量,它包含了Popen类的实例。
你可以用这个实例做什么?

# Check if child is terminated and possibly get the returncode
child.poll()
# Write to child's standard input by a file-like object accessible with
child.stdin
# Read child's standard output and standard error by file-like objects accesible with
child.stdout
child.stderr

你说你想从它的输出中检测子进程中是否出现问题。
难道你不觉得stdoutstderr对这个案子非常有用吗?
现在你想要在发现问题出现时终止孩子。

child.kill()
child.terminate()
child.send_signal(signal)

如果你最终确定一切顺利,但你想让孩子正常完成,你应该使用

child.wait()

甚至更好

child.communicate()

因为communicate会正确处理大量输出。

祝好运!