繁体   English   中英

如何在 python 中运行 bash 脚本并使用在该脚本中定义的变量

[英]How to run a bash script in python and use the variables that where defined in that script

我在 Python 脚本中运行 bash 脚本,我需要在 Python 脚本中使用在 bash 脚本内部定义的变量。

对于某些上下文,这里是 bash 脚本:

#!/bin/bash
updates=$(/usr/lib/update-notifier/apt-check 2>&1)
all=${updates%";"*}
security=${updates#*";"}

这是我在 Python 脚本中调用它的方式:

import subprocess
subprocess.call(["/usr/bin/checkupdates"])

我想在此 SQL 更新语句(它是 Python 脚本的一部分)中使用在该 bash 脚本(“all”和“security”)中定义的变量:

cursor.execute("update dbo.updates_preprod set updates_available = ?, securityupdates_available = ? where hostname = ?",(all, security , socket.gethostname()))
cnxn.commit()

是否有可能做到这一点? 如果没有,我是否可以运行 2 个单独的脚本(每个脚本都会回显一个变量)并获取每个脚本的标准输出并将其定义为 Python 中的变量?

提前致谢!

最后,直接从 Python 脚本调用该命令要容易得多。

output = subprocess.check_output("usr/lib/update-notifier/apt-check", shell=True) all,sec = output.decode().split(';')

感谢@cdarke 和@furas 的建议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM