微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个python脚本,它需要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:没有名为子进程的模块”.我猜我的版本(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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐