Sumanth Kodali
Sumanth Kodali

Reputation: 1

How to execute if else unix command from python and get ret value

Following is the code which I am trying to execute using 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")

When executed gives following error message

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

Upvotes: 0

Views: 888

Answers (1)

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137527

In sh scripts, if is terminated with fi, not endif.

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


Or just write the darn code in Python:

import os

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

If you really want to run tcsh commands, then:

import shlex
import subprocess

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

Upvotes: 6

Related Questions