Let's say my shell script returns a value of '19' when it is run. 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.
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.
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.
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
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
#!/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. The return value from subprocess.check_output()
will therefore include the new line produced by the shell script. Calling str.rstrip()
will remove any trailing whitespace, leaving just '19'
in this case.
尝试调用subprocess.Popen
,它返回不带0的值。
This works for me. I suspect you have a problem in your shell script that is causing the output.
$ 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
>>>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.