Reputation: 4680
I would like to run the bash "test" command inside a python script.
For example, in the bash sell script, this can be done easily as follows. #!/bin/bash
if ! test -s ${file}; then
echo "${file} does not have a positive size. "
# Do some processing..
fi
With a python script, I think I may try the following way:
#!/usr/bin/python
import subrocess
try:
subprocess.check_call("test -s " + file, shell=True)
except:
print file + " does not have a positive size. "
# Do some process
Is the above approach a good way? If not, then could you please suggest an appropriate way?
Upvotes: 0
Views: 526
Reputation: 1623
You shouldn't use shell=True
unless it's necessary. Here, you can use subprocess.check_call(["test","-s",file])
without the security downsides of shell=True
.
Aside from that, you can use built-ins to python rather than making subprocess calls. For instance, os
has what you want here:
import os
try:
if os.stat(file).st_size == 0:
print "File empty."
except OSError:
print "File could not be opened."
Upvotes: 2