Python Resources

Updated on Feb 5 2022

Python Resources

Deborah R. Fowler



Systems Calls and ways to enhance E3

Posted on Oct 13  2018
Updated on April 27  2020 (updated print for python 3)

Now that we have reviewed linux command, let's look at how this can be useful in our code as well. Documentation is at https://docs.python.org/2/library/os.html

By importing the os library you are then access much of what you do command line, such as making directories. You can write scripts to manipulate files such as the ones seen on this example page.

Here is an example of making a directory without having to pre-create it if you wanted to write your files to a specific folder (remember folders are called directories in linux).

MISSING IMAGE

I would encourage you to use the os library to create a folder to place your images as you are working.
Now if you were to run this again, it would object to creating the directory because test already exists. You can delete it by hand, but that is not what we want to do.
Two options: rename it or write over it. Show below is the renaming option.
To detect if it exists you can use os.path.exists("test"). That will work for files or directories. You can also use "isdir"
MISSING IMAGE
To rename it we can use os.rename(oldname, newname). Of course if you don't create a unique name it will cause a problem the next time. To handle this we use a while loop to check for existing folders (directories).
MISSING IMAGE
You can use practically any command that is on your system with os.system(theCommandYouWant).

Running mplay, Houdini's file viewer on Windows or Linux

For example, if you wanted a script to run mplay on all your PNG files.

MISSING IMAGE

What would this look like on linux?
MISSING IMAGE

However, Linux does NOT require you to use the entire path specification and you can simply use mplay:
MISSING
      IMAGE
Or if your images were in a directory relative to your script
MISSING
      IMAGE
A more robust script would not use absolute paths when possible. Think about what happens when we change versions? We don't want to have to update our scripts.
Deleting files and directories:

What if you want to remove files?
os.system("rm *.png") will remove all the images files from the current directory.

os.chdir("MyDirectoryToDelete")
os.system("rm *.png")  # In Windows this would be os.system("del *.png")

If you wanted to delete your empty directory you could then use
os.chdir("../")
os.rmdir("MyDirectoryToDelete")

MISSING IMAGE
You can also use shutil but the above will get you started. If you are interested in shutil, the documentation is https://docs.python.org/2/library/shutil.html
For example, with shutil, to remove a directory of files you could just use rmtree:

MISSING IMAGE

Simple way to make your script OS friendly:

There are more sophisticated ways to make your script OS independent, here is one way:

MISSING IMAGE