私はPythonでbashコマンドを呼び出すためにsubprocessを使用しています。シェルが表示しているものとは異なる戻りコードを取得しています。 "lsのは/ dev/DSK &>は/ dev/nullに" 送ると
import subprocess
def check_code(cmd):
print "received command '%s'" % (cmd)
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
print "p.returncode is '%d'" % (p.returncode)
exit()
if p.returncode == 0:
return True
else:
return False
#End if there was a return code at all
#End get_code()
、check_codeは "エコー$?" 0を返しますが、端末に「2」が生成されます。
Welcome to Dana version 0.7
Now there is Dana AND ZOL
received command 'ls /dev/dsk &> /dev/null'
p.returncode is '0'
[email protected]:~# ls /dev/dsk &> /dev/null
[email protected]:~# echo $?
2
[email protected]:~#
ここで何が起こっているのか分かりますか?
私はあなたが 'ls'のシェルではなくシェルのリターンコードを見ていると思います。 – jtbandes
'p.wait()'の戻り値も間違っていますか? –
'shell = True'を使うのはお勧めできません。特に、信頼できないユーザー入力がある場合。 –