python - 如何从 python 脚本中的 shell 脚本返回值

标签 python linux bash shell unix

我有一个 python 脚本,它需要一个来自 shell 脚本的值。

以下是shell脚本(a.sh):

#!/bin/bash
return_value(){
  value=$(///some unix command)
  echo "$value"
}

return_value

以下是python脚本:

Import subprocess
answer = Subprocess.call([‘./a.sh’])
print("the answer is %s % answer")  

但它不起作用。错误是“ImportError:没有名为 subprocess 的模块”。我想我的版本 (Python 2.3.4) 已经很旧了。在这种情况下是否可以应用子流程的替代品??

最佳答案

使用subprocess.check_output:

import subprocess
answer = subprocess.check_output(['./a.sh'])
print("the answer is {}".format(answer))

关于 subprocess.check_output 的帮助:

>>> print subprocess.check_output.__doc__
Run command with arguments and return its output as a byte string.

演示:

>>> import subprocess
>>> answer = subprocess.check_output(['./a.sh'])
>>> answer
'Hello World!\n'
>>> print("the answer is {}".format(answer))
the answer is Hello World!

a.sh :

#!/bin/bash
STR="Hello World!"
echo $STR

关于python - 如何从 python 脚本中的 shell 脚本返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17238263/

相关文章:

c - 一种语言在我们需要语言绑定(bind)的库中留下了什么 'mark'?

mysql - 跳过mysql中的第一行导出到linux中的.txt文件

linux - Perl 目录查找器不起作用?

c - 使用 .sh 脚本测试 C 程序时显示输入

python - 修改某些 pandas 数据框列,将更改应用于整个原始数据框

python - 找不到满足要求的版本,报错python

linux - 从主题中的命令行发送带有 bash 参数的邮件

regex - sed 命令仅在 unix 中的最后一行添加文本

python - 在Python中使用正则表达式进行字符串替换并具有重叠模式

python - 使用 Python 和 RegEx 从多个 .txt 文件中提取某些数据