我有一个python程序,该程序通过subprocess()模块调用shell脚本。我正在寻找一种传递简单文件作为shell脚本输入的方法。这是通过子过程和popen发生的吗?
我已经为AWS lambda函数尝试了此代码
答案 0 :(得分:1)
如果您可以在问题中分享一些代码摘录,那将是一件非常有益的事情。
但是假设它有点。
这是实现这一目标的一种方法。
import shlex
from subprocess import PIPE, Popen
import logger
def run_script(script_path, script_args):
"""
This function will run a shell script.
:param script_path: String: the path of script that needs to be called
:param script_args: String: the arguments needed by the shell script
:return:
"""
logger.info("Running bash script {script} with parameters:{params}".format(script=script_path, params=script_args))
# Adding a whitespace in shlex.split because the path gets distorted if args are added without it
session = Popen(shlex.split(script_path + " " + script_args), stderr=PIPE, stdout=PIPE, shell=False)
stdout, stderr = session.communicate()
# Beware that stdout and stderr will be bytes so in order to get a proper python string decode the values.
logger.debug(stdout.decode('utf-8'))
if stderr:
logger.error(stderr)
raise Exception("Error " + stderr.decode('utf-8'))
return True
现在要在此处注意几件事
$1
还是诸如--file
或-f
之类的已命名参数shlex
方法在字符串数组中提供所需的所有参数即可。