[Tutor] Python working with Bash....arrrggggh!
Ray Jones
crawlzone at gmail.com
Fri Aug 24 08:34:37 CEST 2012
On 08/23/2012 10:37 PM, eryksun wrote:
> On Thu, Aug 23, 2012 at 11:55 PM, Ray Jones <crawlzone at gmail.com> wrote:
>
>> For example, if I wish to test if a file exists, I might do
>>
>> test = Popen('[ -f file-i-want-to-test-for ]')
>>
>> But the moment I invoke Bash for a test, I must deal with the fact that
>> Bash returns a zero for true and a non-zero for false. But in Python,
> Please see os.path:
>
> http://docs.python.org/library/os.path
>
> That said, you can use check_call and check_output if you want a more
> Pythonic interface. These raise an exception for a non-zero return
> code. For example:
>
> # check.py
>
> from subprocess import check_call, CalledProcessError
>
> try:
>
> # in Debian [ is at /usr/bin/[
> rc = check_call(["/usr/bin/[", "-f", "check.py", "]"])
> print "success:", rc
>
> # or pass the command string to the shell
> rc = check_call("[ -f check.py ]", shell=True)
> print "success:", rc
>
> # force a failure
> rc = check_call("[ -f notfound ]", shell=True)
> print "success:", rc # this won't execute
>
> except CalledProcessError as e:
> print "failed: %d" % e.returncode
Ah, yes. Thanks for the reminder that the check_call automatically
interprets the True/False returns from the OS.
Ray
More information about the Tutor
mailing list