Python Notes

Here are a some notes I compiled for the basics of python scripting. I think Python is much better than Bash in terms of scripting because much friendlier syntax and easy to write into small modules. The abundance of data structures also makes life a lot easier with list, pair and especially dictionaries.

  1. ls
    1. os.listdir(path)
  2. cd
    1. os.chdir(path)
  3. subprocess
    1. This is a tricky yet extremely important module
    2. check_output is only available after 2.7 (2.6.9 would not have it)
    3. check_output would output the stdout (you can also attach the stderr)
      1. Note: this can sometimes hide error messages in stderr if you try to catch the exception. It is better to not really try and catch the error.
    4. For debugging, it is easier to just use first. Check_output is useful after you figured out the correctness issues.
    5. Other notes from previous posts
      1. background execution,
      2. POpen (an even lower API)
  4. Environment variables
    1. In order for child processes to see the environment variables set in the parent processes, they have to be “export” .
    2. The tricky part is sometimes, “LD_LIBRARY_PATH” is not visible in the python process, not sure why. I had to do the following to set and export it again
      1."export LD_LIBRARY_PATH=" + var + "; " + run_cmd, shell=True)
  5. Reading and Writing to a file
  6. Dictionary
    1. {‘a’:1}
    2. make a deep copy dictionary.copy() or dict(oldDict)
  7. Plot multiple lines (import matplotlib.pyplot as plt)
    2. to display the graph
  8. Save plots to figures
  9. Plot with points, labels
    1. points:  plot(xData,yData, marker=’o’, linestyle=’–‘)
    2. labels:  plt.legend
      1.     plt.legend(legendData, loc=’best’)
    3. color (use more than 5 colors)
      1. use the color mapcolormap =[colormap(i) for i in np.linspace(0, 0.9, number)])

      2. of course, you can use new packages as suggested here
This entry was posted in Tools, Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s