diff --git a/lectures/week10.html b/lectures/week10.html new file mode 100644 index 0000000..254d448 --- /dev/null +++ b/lectures/week10.html @@ -0,0 +1,472 @@ + + + + + + + + + + + +talk slides + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Python Path and Subprocess (useful for scripting)

+
+
+ +
+

We want to be able to:

    +
  • read/write files
  • +
  • launch executables
  • +
  • generate input
  • +
  • parse ouput
  • +
  • make graphs of publication quality
  • +
  • post-treatment: curve fit, vector manipulation...
  • +
+ +
+
+
+
+ +
+

Selected python scripting tools

+
+
+
+
+ +
+

Manipulating filenames

import os
+path, name = os.path.split('/tmp/test.plot')
+basename, ext = os.path.splitext(name)
+print('path ' + path)
+print('name ' + name)
+print('basename ' + basename)
+print('ext ' + ext)
+
+ +
+
+
+
+ +
+

How to list all files in a directory

import os
+for fname in os.listdir('/tmp'):
+    print(fname)
+
+ +
+
+ +
+

list only files of a given extension

import os
+for fname in os.listdir('/tmp'):
+    name,ext = os.path.splitext(fname)
+    if not ext == '.txt':
+        continue
+    print('name ' + name)
+    print('ext ' + ext)
+
+ +
+
+
+
+ +
+

construct filenames with other files and a different path

import os
+
+new_path = '/newpath'
+
+for fname in os.listdir('/tmp'):
+    basename = os.path.basename(fname)
+    new_file = os.path.join(new_path, basename)
+    print(new_file)
+
+ +
+
+
+
+ +
+

execute other programs: Subprocess module

import subprocess
+
+ +
+
+ +
+

Launching another program is simply done by the call function

+
res = subprocess.call(['ls', '-trlh'])
+
+

The output is sent to screen.

+ +
+
+
+
+ +
+

Saving output into a file

import subprocess
+
+outfile = open('out.txt', 'w')
+res = subprocess.call(['ls', '-trlh'], stdout=outfile)
+
+ +
+
+
+
+ +
+

Saving output into a string

import subprocess
+
+process = subprocess.Popen(["ls", "-trlh"], stdout=subprocess.PIPE)
+out, err = process.communicate()
+print (out.decode)
+
+ +
+
+
+
+ +
+

Exploiting return code

import subprocess
+
+process = subprocess.Popen(["ls", "-trlh"], stdout=subprocess.PIPE)
+out, err = process.communicate()
+ret = process.ret
+if ret != 0:
+    print('Failed')
+else:
+    print('return code: {0}'.format(ret))
+
+ +
+
+
+
+
+ + + + + + +