简体   繁体   English

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

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

I'm running a bash script inside of a Python script, and I need to use the variables that were defined inside of the bash script, in the Python script.我在 Python 脚本中运行 bash 脚本,我需要在 Python 脚本中使用在 bash 脚本内部定义的变量。

For some context, here is the bash script:对于某些上下文,这里是 bash 脚本:

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

Here is how I am calling it in the Python script:这是我在 Python 脚本中调用它的方式:

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

I want to use the variables that were defined in that bash script ('all' and 'security') in this SQL update statement (which is part of the Python script):我想在此 SQL 更新语句(它是 Python 脚本的一部分)中使用在该 bash 脚本(“all”和“security”)中定义的变量:

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

Is it possible to do this?是否有可能做到这一点? If not, could I run 2 separate scripts (each script would echo one of the variables) and grab the stdout of each script and define it as a variable in Python?如果没有,我是否可以运行 2 个单独的脚本(每个脚本都会回显一个变量)并获取每个脚本的标准输出并将其定义为 Python 中的变量?

Thanks in advance!提前致谢!

In the end it was much easier to call that command directly from the Python script.最后,直接从 Python 脚本调用该命令要容易得多。

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

Thanks to @cdarke and @furas for the suggestion.感谢@cdarke 和@furas 的建议。

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

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