I was wondering whether or not it is considered a good style to call bash commands within a Python script using os.system(). I was also wondering whether or not it is safe to do so as well.
I know how to implement some of the functionality I need in Bash and in Python, but it is much simpler and more intuitive to implement it in Bash. However, I feel like it is very hackish to write os.system("bash code").
Specifically, I want to move all files that end with a certain extension to a directory.
In bash: *mv .ext /path/to/destination In Python (Pseudocode): for file in directory: if file.endswith("ext"): move file to destination
In this case, what should I do?
It always better and better style to use Python functions to do this kind of stuff. With Python it's not that hard to write a script in an OS-independent way instead of using bash.
First of all, your example uses mv, which is a program in coreutils, not bash.
Using os.system() calls to external programs is considered poor style because:
Look up glob, for shell-like pattern matching (globbing), and shutil, as others have already mentioned. Otherwise, everything you need is already in the standard libraries.
In addition, os.system() should not be used - take a look at the subprocess module instead.
Some reasons why you should use pure Python,
In this case, I would use ...
There may be better ways though
More generally, Python provides the 'subprocess' module that will allow you to run commands and exercise extensive control over their output. It lets you "spawn new processes, connect to their input/output/error pipes, and obtain their return codes":
http://docs.python.org/library/subprocess.html
Check out Python's
shutil
module. It offers file system operations such as moving files. Between that and theos
module, you should have all the tools you need. This is preferable to the bash commands for the reasons others said.It's not idea, since it makes your script a lot less portable. A native python script can run on any unix or windows machine that has the proper python libraries installed. When you add shell commands into the mix, you break that, and suddenly are locked down to a much narrower subset.
Sometimes you don't have a choice, but if it's something as simple as that, writing the code natively in python would make a lot more sense, and also be faster to boot (since the python process won't have to spawn a new shell just to execute the one command).