簡體   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