繁体   English   中英

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

[英]Call shell script from python code without any return value (0) or new lines

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

这里有许多与我的参考相似的问题,但是我还没有找到解决方案,其中shell脚本将返回“ 19”而没有额外的返回值0或换行。

在python代码中使用subprocess.call('bash TestingCode', shell=True)准确返回我想要的内容,但是当我将此命令存储在变量中然后打印该变量时,它会打印出额外的0。

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

>>19
>>0

然后,我尝试了以下问题的示例: 如何从python脚本中的shell脚本返回值

但是,它反而给我额外的空行。

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

我非常感谢您的帮助!

更新: TestingCode脚本

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

只是这样称呼它:

import subprocess

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

原因是您的shell脚本正在打印19然后换行。 因此, subprocess.check_output()的返回值将包含由外壳脚本产生的新行。 调用str.rstrip()将删除所有结尾的空格,在这种情况下仅保留'19'

尝试调用subprocess.Popen ,它返回不带0的值。

这对我有用。 我怀疑您的shell脚本中存在导致输出的问题。

$ cat test.sh
#!/bin/sh
exit 19
(0) austin@Austins-Mac-8:~
$ python2.7
Python 2.7.10 (default, Aug 22 2015, 20:33:39)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.call('bash test.sh', shell=True)
19
>>> 

暂无
暂无

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

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