from __future__ import print_function, division
import subprocess
import sys
import numpy as np
You must assign the return value(s) to variable(s). See Session 4 lecture.
def plus_two(x):
return x + 2
# This does not store return value.
# There is no way to use the result somewhere else.
plus_two(3)
5
# This stores return value.
ans = plus_two(3)
print(ans)
# And you can use it for something else.
ans2 = ans * 2
print(ans2)
5 10
x = y = np.arange(100)
def fit_line_wrong(x, y):
coeffs = np.polyfit(x, y, 1)
print('Inside function:', coeffs)
coeffs = fit_line_wrong(x, y)
print('Outside function:', coeffs)
Inside function: [ 1.00000000e+00 -6.58026679e-15] Outside function: None
def fit_line_correct(x, y):
coeffs = np.polyfit(x, y, 1)
print('Inside function:', coeffs)
# You have to return coeffs.
# Otherwise it is not accessible by codes outside of function.
return coeffs
coeffs = fit_line_correct(x, y)
print('Outside function:', coeffs)
Inside function: [ 1.00000000e+00 -6.58026679e-15] Outside function: [ 1.00000000e+00 -6.58026679e-15]
x = 1
type(x)
int
isinstance(x, int)
True
isinstance(x, type(1))
True
if isinstance(x, np.ndarray):
print('x is numpy array')
else:
print('x is not numpy array')
x is not numpy array
s = 'I am a string'
if isinstance(s, (int, long, float, complex, np.number, np.ndarray)):
print('s is a type of numeric value/array that I recognize')
else:
print('uh oh!')
uh oh!
How to capture both screen outputs and return code for expensive system calls?
This does not work in notebook, but it works in a regular Python session.
>>> status = subprocess.call(["which", "cs6.e"], sys.stdout.fileno())
/usr/stsci/hstcaldev/bin/cs6.e
>>> print(status)
0
This explains wildcard usage in subprocess
:
http://stackoverflow.com/questions/9997048/python-subprocess-wildcard-usage
logfile = open('log.txt', 'w')
errfile = open('err.txt', 'w')
# Captures standard screen output in log.txt
# and error messages in err.txt.
status = subprocess.call(
["ls", "Session5_Homework_Comments.ipynb", "does_not_exist"],
stdout=logfile, stderr=errfile)
logfile.close()
errfile.close()
print(status)
2
!more log.txt
Session5_Homework_Comments.ipynb
!more err.txt
ls: does_not_exist: No such file or directory