Skip to content

Commit

Permalink
Use print() function in both Python 2 and Python 3 (istio#10943)
Browse files Browse the repository at this point in the history
Legacy __print__ statements are syntax errors in Python 3 but __print()__ function works as expected in both Python 2 and Python 3.
cclauss authored and linsun committed Feb 4, 2019
1 parent 0fe8fe9 commit 43262a6
Showing 7 changed files with 35 additions and 28 deletions.
25 changes: 13 additions & 12 deletions bin/diff_yaml.py
Original file line number Diff line number Diff line change
@@ -17,6 +17,7 @@
# Compare 2 multi document kubernetes yaml files
# It ensures that order does not matter
#
from __future__ import print_function
import argparse
import datadiff
import sys
@@ -63,7 +64,7 @@ def normalize_configmap(res):
op = yaml.safe_load_all(data[k])
data[k] = list(op)
except yaml.YAMLError as ex:
print ex
print(ex)

return res
except KeyError as ke:
@@ -127,28 +128,28 @@ def compare(args):
if q0[k] != q1[k]:
changed += 1

print "## +++ ", args.new
print "## --- ", args.orig
print "## Added:", len(added)
print "## Removed:", len(removed)
print "## Updated:", changed
print "## Unchanged:", len(common) - changed
print("## +++ ", args.new)
print("## --- ", args.orig)
print("## Added:", len(added))
print("## Removed:", len(removed))
print("## Updated:", changed)
print("## Unchanged:", len(common) - changed)

for k in sorted(added):
print "+", k
print("+", k)

for k in sorted(removed):
print "-", k
print("-", k)

print "## *************************"
print("## *************************")

for k in sorted(common):
if q0[k] != q1[k]:
print "## ", k
print("## ", k)
s0 = yaml.safe_dump(q0[k], default_flow_style=False, indent=2)
s1 = yaml.safe_dump(q1[k], default_flow_style=False, indent=2)

print datadiff.diff(s0, s1, fromfile=args.orig, tofile=args.new)
print(datadiff.diff(s0, s1, fromfile=args.orig, tofile=args.new))

return changed + len(added) + len(removed)

13 changes: 7 additions & 6 deletions bin/ghdata.py
Original file line number Diff line number Diff line change
@@ -14,6 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function
import requests
import os
import sys
@@ -37,8 +38,8 @@ def get_rawdata(token, repo="istio"):


def usage():
print "Visit https://github.com/settings/tokens to generate a token"
print "You must have admin access on the repository get download counts"
print("Visit https://github.com/settings/tokens to generate a token")
print("You must have admin access on the repository get download counts")


def main(args):
@@ -50,24 +51,24 @@ def main(args):
token = open(token).read()

if token is None:
print "Unable to get GITHUB_TOKEN as env var, first argument or @file"
print("Unable to get GITHUB_TOKEN as env var, first argument or @file")
usage()
return -1

try:
data = get_rawdata(token)
except Exception as ex:
print ex
print(ex)
usage()
return -1

print "# Report created at UTC:", str(datetime.datetime.utcnow())
print("# Report created at UTC:", str(datetime.datetime.utcnow()))
for d in ["{}, {}, {}".format(
q['created_at'],
q['download_count'],
q['browser_download_url'].split('/')[-1])
for j in data for q in j['assets']]:
print d
print(d)

return 0

9 changes: 5 additions & 4 deletions bin/istio-proxy-cfg.py
Original file line number Diff line number Diff line change
@@ -14,6 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function
import os
import sys

@@ -329,7 +330,7 @@ def main(args):
data = xds.lds(pod, True)
yaml.safe_dump(data, op, default_flow_style=False,
allow_unicode=False, indent=2)
print "Wrote ", output_file
print("Wrote ", output_file)

if pilot_port_forward_pid:
subprocess.call(["kill", "%s" % pilot_port_forward_pid])
@@ -345,20 +346,20 @@ def main(args):
data = pr.routes()
yaml.safe_dump(data, op, default_flow_style=False,
allow_unicode=False, indent=2)
print "Wrote ", output_file
print("Wrote ", output_file)

output_file = output_dir + "/" + "proxy_listeners.yaml"
op = open(output_file, "wt")
data = pr.listeners()
yaml.safe_dump(data, op, default_flow_style=False,
allow_unicode=False, indent=2)
print "Wrote ", output_file
print("Wrote ", output_file)

output_file = output_dir + "/" + "proxy_clusters.yaml"
op = open(output_file, "wt")
data = pr.clusters()
op.write(data)
print "Wrote ", output_file
print("Wrote ", output_file)

if envoy_port_forward_pid:
subprocess.call(["kill", "%s" % envoy_port_forward_pid])
5 changes: 3 additions & 2 deletions samples/bookinfo/src/productpage/productpage.py
Original file line number Diff line number Diff line change
@@ -15,6 +15,7 @@
# limitations under the License.


from __future__ import print_function
from flask import Flask, request, session, render_template, redirect, url_for
from flask import _request_ctx_stack as stack
from jaeger_client import Tracer, ConstSampler
@@ -344,12 +345,12 @@ def flush(self):

if __name__ == '__main__':
if len(sys.argv) < 2:
print "usage: %s port" % (sys.argv[0])
print("usage: %s port" % (sys.argv[0]))
sys.exit(-1)

p = int(sys.argv[1])
sys.stderr = Writer('stderr.log')
sys.stdout = Writer('stdout.log')
print "start at port %s" % (p)
print("start at port %s" % (p))
app.run(host='0.0.0.0', port=p, debug=True, threaded=True)

3 changes: 2 additions & 1 deletion security/tools/jwt/sa-jwt.py
Original file line number Diff line number Diff line change
@@ -19,6 +19,7 @@
Example:
./sa-jwt.py --iss example-issuer --aud foo,bar --claims=email:[email protected],dead:beef key.json
"""
from __future__ import print_function
import argparse
import time

@@ -76,4 +77,4 @@ def main(args):
help="sub claim. If not provided, it is set to the same as iss claim.")
parser.add_argument("-claims", "--claims",
help="Other claims in format name1:value1,name2:value2 etc. Only string values are supported.")
print main(parser.parse_args())
print(main(parser.parse_args()))
3 changes: 2 additions & 1 deletion security/tools/jwt/samples/gen-jwt.py
Original file line number Diff line number Diff line change
@@ -19,6 +19,7 @@
Example:
./gen-jwt.py --iss example-issuer --aud foo,bar --claims=email:[email protected],dead:beef key.pem -listclaim key1 val2 val3 -listclaim key2 val3 val4
"""
from __future__ import print_function
import argparse
import time

@@ -102,4 +103,4 @@ def main(args):
help="JWT expiration time in second. Default is 1 hour.")
parser.add_argument("-listclaim", "--listclaim", action='append', nargs='+',
help="A list claim in format key1 value2 value3... Only string values are supported. Multiple list claims can be specified, e.g., -listclaim key1 val2 val3 -listclaim key2 val3 val4.")
print main(parser.parse_args())
print(main(parser.parse_args()))
5 changes: 3 additions & 2 deletions tools/convert_perf_results.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
import json
import os
import sys
@@ -29,13 +30,13 @@ def csv_line(data):
return ("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s" % (labels, qps, duration, clients, min, max, avg, p50, p75, p90, p99, p99d9))

# Print the header line
print "Label,Driver,Target,qps,duration,clients,min,max,avg,p50,p75,p90,p99,p99.9"
print("Label,Driver,Target,qps,duration,clients,min,max,avg,p50,p75,p90,p99,p99.9")

# For each json file in current dir, interpret it as Fortio result json file and print a csv line for it.
for fn in os.listdir(target_dir):
fullfn = os.path.join(target_dir, fn)
if os.path.isfile(fullfn) and fullfn.endswith('.json'):
with open(fullfn) as f:
data = json.load(f)
print csv_line(data)
print(csv_line(data))

0 comments on commit 43262a6

Please sign in to comment.