$? in linux gives the exit status of the recently executed command , as i have learnt.
suppose i give a cd command at the terminal and if such a directory or file is not present, echo $? following it gives me 1.

but, when the same is run via a script using os.system("cd.........."),
os.system("echo $?") gives 0.

it might be simple, but I am not able to trace out the reason.. can anyone throw some light on this?

Recommended Answers

All 2 Replies

$? is a shell variable. Each time you call os.system, python creates a new shell. Anyway, os.system() is deprecated, use subprocess.Popen

import subprocess as sp
process = sp.Popen("cd /foo; echo $?", shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
print process.communicate()

""" my output -->
('1\n', '/bin/sh: line 0: cd: /foo: Aucun fichier ou dossier de ce type\n')
"""
# (my shell speaks french :) )

I also wrote a small Command class which does about the same. See http://www.daniweb.com/code/snippet257449.html

Thanks grib...... it worked with subprocess.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.