2016-07-22 53 views
0

下面是我試圖使用python如何從蟒蛇,如果其他UNIX命令執行,並得到RET值

from subprocess import Popen, PIPE 

cmd = 'if (-e "../a.txt") then \n ln -s ../a.txt . \n else \n echo "file is not present " \n endif' 

ret_val = subprocess.call(cmd,shell="True") 

在執行時,執行代碼提供以下錯誤消息

/bin/sh: -c: line 5: syntax error: unexpected end of file 
+3

確實在你的shell命令工作? – user2393256

+2

您應該將'True'傳遞給'shell',而不是字符串'「True」'。 – DeepSpace

+3

這是醜陋的......強烈建議將邏輯放入python代碼中。 – wim

回答

6

在SH腳本iffi終止,而不是。

http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html


或者只是用Python語言編寫的代碼織補:

import os 

if os.path.exists('../a.txt'): 
    print 'Exists' 
    os.symlink('../a.txt', 'a.txt') 
else: 
    print 'Does not exist' 

如果你真的想運行tcsh的命令,然後:

import shlex 
import subprocess 

args = ['tcsh', '-c'] + shlex.split(some_tcsh_command) 
ret = suprocess.call(args) 
+0

我在tcsh shell中執行。如果直接在shell中運行它的命令。但是當我通過pyhton腳本執行它不工作。 –

+0

是的,這是方式。如果你有比python更多的shell cmd,請不要使用python:D – pwnsauce

+2

不,你不是。看看正在打印的錯誤消息。它是'/ bin/sh'。 *你使用的shell在這裏沒有任何意義。傳遞'shell = True'告訴Subprocess通過'/ bin/sh'運行它。 –