python - 从 python 代码调用 shell 脚本,没有任何返回值 (0) 或换行符

标签 python bash python-2.7 shell

假设我的 shell 脚本在运行时返回值“19”。我想将该值(没有任何返回值 0 或空行)存储到我的 python 代码中的变量中以供以后使用。

这里有很多问题与我的类似,但我还没有找到解决方案,让 shell 脚本返回“19”,而没有额外的返回值 0 或新行。

在Python代码中使用subprocess.call('bashTestingCode', shell=True)返回的正是我想要的,但是当我将此命令存储在变量中然后打印该变量时,它打印时带有额外的 0。

answer = subprocess.call('bash TestingCode', shell=True)
print answer

>>19
>>0

然后我尝试了这个问题的一个例子:How to return a value from a shell script in a python script

但是它返回给我一个额外的空行。

answer = subprocess.check_output('bash TestingCode', shell=True)
print answer
>>19
>> 

非常感谢您的帮助!

更新:测试代码脚本

#!/bin/bash
num=19
echo $num

最佳答案

就这样调用它:

import subprocess

answer = subprocess.check_output('bash TestingCode', shell=True)
answer = answer.rstrip()

原因是您的 shell 脚本正在打印 19,后跟一个新行。因此,subprocess.check_output() 的返回值将包含 shell 脚本生成的新行。调用 str.rstrip() 将删除所有尾随空格,在本例中仅留下 '19'

关于python - 从 python 代码调用 shell 脚本,没有任何返回值 (0) 或换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34983719/

相关文章:

python - 从 syntastic 中删除条目

python - 从列表中替换 Pandas 系列的值

linux - shell 脚本中的错误以及如何写入文件

bash shell 重做变量用下划线替换点

Python:如何将使用 MIME 生成的电子邮件保存到磁盘

python - Unix - 哪个应用程序在前台?

bash - 遍历数组,防止通配符扩展 (*)

Python:如何在请求中使用 Chrome cookie

python - 使用python的带有字典的配置文件

Python 从另一个多处理函数调用一个多处理函数。