如何传递在python脚本中创建的变量以用于bash脚本?

问题描述

我正在使用Python 3.6.3。

我创建了一个python脚本'create.py'。该python脚本调用并运行bash脚本“ verify.sh”。

“ verify.sh”脚本发送电子邮件

#!/bin/sh
emailGroup="[email protected]"
echo "The variable of interest is x(insert here): $1 " | mail -s "The variable of interest is x(insert here)" ${emailGroup}

因此在我的python脚本中确定了“ x”。我想将x插入上面的'verify.sh'脚本中,以便它与电子邮件一起消失。

解决方法

这是一个示例。

首先是Python脚本:

#!/usr/bin/python3
import subprocess
recipient = "[email protected]"
subject = "Python Script Calls Bash Script"
body = "This is a test,yes it is,yes it is."
notify_script = "/home/me/Scripts/notify"
subprocess.run([notify_script,recipient,subject,body])

第二个Bash脚本:

#!/bin/bash
recipient="$1"
subject="$2"
body="$3"
dummy_mailer -r "$recipient" -s "$subject" -b "$body"

可以使用ARG_MAX从Python脚本发送任意数量的args(请参阅subprocess.run()),只需将它们添加到给run()的列表中即可。例如

subprocess.run([path_to_script,arg_1])
subprocess.run([path_to_script,arg_1,arg_2])
subprocess.run([path_to_script,arg_2,arg_3,arg_4])
,

如果这确实是您的verify.sh脚本的全部范围,则可以将其完全删除。

import subprocess

sent = subprocess.run(
    ['mail','-s','The variable of interest is x(insert here)','[email protected]'],input='The variable of interest is x(insert here): {0}'.format(x),text=True,check=True)

如果您使用的是3.7之前的Python版本,则需要使用universal_newlines=True而不是text=True

您也不需要mail -s;参见例如How to send an email with Python?