如何从python执行if else unix命令并获取ret值

0 python unix

以下是我尝试使用python执行的代码

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")
Run Code Online (Sandbox Code Playgroud)

执行时给出以下错误消息

/bin/sh: -c: line 5: syntax error: unexpected end of file
Run Code Online (Sandbox Code Playgroud)

Jon*_*art 6

在sh脚本中,if终止fi,而不是endif.

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


或者只是在Python中编写darn代码:

import os

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

如果你真的想运行tcsh命令,那么:

import shlex
import subprocess

args = ['tcsh', '-c'] + shlex.split(some_tcsh_command)
ret = suprocess.call(args)
Run Code Online (Sandbox Code Playgroud)

  • 不你不是.查看正在打印的错误消息.是`/ bin/sh`.你*正在使用的shell在这里没有任何意义.传递`shell = True`告诉Subprocess通过`/ bin/sh`运行它. (2认同)