[Tutor] Python working with Bash....arrrggggh!

Ray Jones crawlzone at gmail.com
Fri Aug 24 08:27:56 CEST 2012


On 08/23/2012 09:53 PM, akleider at sonic.net wrote:
>> As I code Python, I find myself falling back on Bash to handle basic OS
>> tasks. How do you gurus deal with Python --> Bash conflicts?
>>
>> 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,
>> zero is false and non-zero is true. So if the file exists, the variable
>> 'test' will be zero since that is what was returned by Bash. But if I
>> want to test the variable for the existence of the file, I have to test
>> the opposite: 'if not test:' because Python sees the zero as False.
>>
>> Does it become second nature to work with these conflicts? Or do you
>> find it more expedient bypass the OS shell and work almost exclusively
>> with Python?
> try
>
>>>> import os.path
>>>> os.path.exists(path)
> or
>>>> os.path.isfile(file_name)

That seems much cleaner to me than testing to see if 'os.listdir'
contains a specific file. Thanks.

I am forever confused, however, on which methods can be found where. I
just spent quarter of an hour searching in sys,* os.*, and shutil.*. for
a 'kill' command that I knew I'd seen before....I found it hidden in
subprocess.Popen. Arrrgggh. These various imports are going to drive me
to drink!

Thanks for the response.


Ray


More information about the Tutor mailing list