假设我的 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/