简体   繁体   English

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

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

Let's say my shell script returns a value of '19' when it is run. 假设我的shell脚本在运行时返回的值为“ 19”。 I'd like to store that value (without any return value of 0 or empty lines) into a variable in my python code for use later. 我想将该值(没有任何返回值0或空行)存储到我的python代码中的变量中,以备后用。

There are many questions here with similar reference to mine but I have yet to find a solution where the shell script is returning me '19' without a extra return value of 0 or new lines. 这里有许多与我的参考相似的问题,但是我还没有找到解决方案,其中shell脚本将返回“ 19”而没有额外的返回值0或换行。

Using subprocess.call('bash TestingCode', shell=True) in the python code returns me exactly what I want however when I store this command in a variable and then print the variable, it prints with an extra 0. 在python代码中使用subprocess.call('bash TestingCode', shell=True)准确返回我想要的内容,但是当我将此命令存储在变量中然后打印该变量时,它会打印出额外的0。

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

>>19
>>0

I then tried an example from this question: How to return a value from a shell script in a python script 然后,我尝试了以下问题的示例: 如何从python脚本中的shell脚本返回值

However it returns me an extra empty line instead. 但是,它反而给我额外的空行。

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

I really appreciate the help! 我非常感谢您的帮助!

UPDATE: TestingCode script 更新: TestingCode脚本

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

Just call it like this: 只是这样称呼它:

import subprocess

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

The reason is that your shell script is printing 19 followed by a new line. 原因是您的shell脚本正在打印19然后换行。 The return value from subprocess.check_output() will therefore include the new line produced by the shell script. 因此, subprocess.check_output()的返回值将包含由外壳脚本产生的新行。 Calling str.rstrip() will remove any trailing whitespace, leaving just '19' in this case. 调用str.rstrip()将删除所有结尾的空格,在这种情况下仅保留'19'

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

This works for me. 这对我有用。 I suspect you have a problem in your shell script that is causing the output. 我怀疑您的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