diff options
Diffstat (limited to 'gnuradio-runtime')
77 files changed, 541 insertions, 346 deletions
diff --git a/gnuradio-runtime/apps/evaluation_random_numbers.py b/gnuradio-runtime/apps/evaluation_random_numbers.py index 069493c73e..30b61be858 100644 --- a/gnuradio-runtime/apps/evaluation_random_numbers.py +++ b/gnuradio-runtime/apps/evaluation_random_numbers.py @@ -20,6 +20,9 @@ # Boston, MA 02110-1301, USA. # +from __future__ import print_function +from __future__ import division +from __future__ import unicode_literals from gnuradio import gr import numpy as np from scipy.stats import norm, laplace, rayleigh @@ -40,7 +43,7 @@ laplace_num_bins = 31 rndm = gr.random() # instance of gnuradio random class (gr::random) -print 'All histograms contain',num_tests,'realisations.' +print('All histograms contain',num_tests,'realisations.') #*** GENERATE DATA ***# @@ -73,7 +76,7 @@ rayleigh_expected = np.zeros(rayleigh_num_bins-1) laplace_expected = np.zeros(laplace_num_bins-1) for k in range(len(uniform_hist[0])): - uniform_expected[k] = num_tests/float(uniform_num_bins-1) + uniform_expected[k] = num_tests / float(uniform_num_bins-1) for k in range(len(gauss_hist[0])): gauss_expected[k] = float(norm.cdf(gauss_hist[1][k+1])-norm.cdf(gauss_hist[1][k]))*num_tests @@ -86,10 +89,10 @@ for k in range(len(laplace_hist[0])): #*** PLOT HISTOGRAMS AND EXPECTATIONS TAKEN FROM SCIPY ***# -uniform_bins_center = uniform_bins[0:-1]+(uniform_bins[1]-uniform_bins[0])/2.0 -gauss_bins_center = gauss_bins[0:-1]+(gauss_bins[1]-gauss_bins[0])/2.0 -rayleigh_bins_center = rayleigh_bins[0:-1]+(rayleigh_bins[1]-rayleigh_bins[0])/2.0 -laplace_bins_center = laplace_bins[0:-1]+(laplace_bins[1]-laplace_bins[0])/2.0 +uniform_bins_center = uniform_bins[0:-1]+(uniform_bins[1]-uniform_bins[0]) / 2.0 +gauss_bins_center = gauss_bins[0:-1]+(gauss_bins[1]-gauss_bins[0]) / 2.0 +rayleigh_bins_center = rayleigh_bins[0:-1]+(rayleigh_bins[1]-rayleigh_bins[0]) / 2.0 +laplace_bins_center = laplace_bins[0:-1]+(laplace_bins[1]-laplace_bins[0]) / 2.0 plt.figure(1) @@ -99,7 +102,7 @@ plt.xlabel('Bins'), plt.ylabel('Count'), plt.title('Uniform: Distribution') plt.legend(['histogram gr::random','calculation scipy'],loc=1) plt.subplot(2,1,2) -plt.plot(uniform_bins_center,uniform_hist[0]/uniform_expected,'rs--') +plt.plot(uniform_bins_center,uniform_hist[0] / uniform_expected,'rs--') plt.xlabel('Bins'), plt.ylabel('Relative deviation'), plt.title('Uniform: Relative deviation to scipy') plt.figure(2) @@ -110,7 +113,7 @@ plt.xlabel('Bins'), plt.ylabel('Count'), plt.title('Gauss: Distribution') plt.legend(['histogram gr::random','calculation scipy'],loc=1) plt.subplot(2,1,2) -plt.plot(gauss_bins_center,gauss_hist[0]/gauss_expected,'rs--') +plt.plot(gauss_bins_center,gauss_hist[0] / gauss_expected,'rs--') plt.xlabel('Bins'), plt.ylabel('Relative deviation'), plt.title('Gauss: Relative deviation to scipy') plt.figure(3) @@ -122,7 +125,7 @@ plt.legend(['histogram gr::random','calculation scipy'],loc=1) plt.subplot(2,1,2) -plt.plot(rayleigh_bins_center,rayleigh_hist[0]/rayleigh_expected,'rs--') +plt.plot(rayleigh_bins_center,rayleigh_hist[0] / rayleigh_expected,'rs--') plt.xlabel('Bins'), plt.ylabel('Relative deviation'), plt.title('Rayleigh: Relative deviation to scipy') plt.figure(4) @@ -133,7 +136,7 @@ plt.xlabel('Bins'), plt.ylabel('Count'), plt.title('Laplace: Distribution') plt.legend(['histogram gr::random','calculation scipy'],loc=1) plt.subplot(2,1,2) -plt.plot(laplace_bins_center,laplace_hist[0]/laplace_expected,'rs--') +plt.plot(laplace_bins_center,laplace_hist[0] / laplace_expected,'rs--') plt.xlabel('Bins'), plt.ylabel('Relative deviation'), plt.title('Laplace: Relative deviation to scipy') plt.show() diff --git a/gnuradio-runtime/examples/mp-sched/affinity_set.py b/gnuradio-runtime/examples/mp-sched/affinity_set.py index e6637b44bf..a253c8081c 100755..100644 --- a/gnuradio-runtime/examples/mp-sched/affinity_set.py +++ b/gnuradio-runtime/examples/mp-sched/affinity_set.py @@ -4,6 +4,8 @@ # Title: Affinity Set Test ################################################## +from __future__ import print_function +from __future__ import unicode_literals from gnuradio import eng_notation from gnuradio import gr from gnuradio import blocks @@ -57,7 +59,7 @@ if __name__ == '__main__': tb.start() while(1): - ret = raw_input('Enter a new Core # or Press Enter to quit: ') + ret = input('Enter a new Core # or Press Enter to quit: ') if(len(ret) == 0): tb.stop() sys.exit(0) @@ -67,6 +69,6 @@ if __name__ == '__main__': try: n = int(ret) except ValueError: - print "Invalid number" + print("Invalid number") else: tb.filter_filt_0.set_processor_affinity([n,]) diff --git a/gnuradio-runtime/examples/mp-sched/plot_flops.py b/gnuradio-runtime/examples/mp-sched/plot_flops.py index 9bd2ff12bb..e71770aee3 100755..100644 --- a/gnuradio-runtime/examples/mp-sched/plot_flops.py +++ b/gnuradio-runtime/examples/mp-sched/plot_flops.py @@ -23,6 +23,7 @@ Reads output from run_synthetic.py and runs gnuplot showing GFLOPS as f(npipes, nstages) """ +from __future__ import unicode_literals import re import sys diff --git a/gnuradio-runtime/examples/mp-sched/run_synthetic.py b/gnuradio-runtime/examples/mp-sched/run_synthetic.py index 802fb9fd34..684f95bd87 100755..100644 --- a/gnuradio-runtime/examples/mp-sched/run_synthetic.py +++ b/gnuradio-runtime/examples/mp-sched/run_synthetic.py @@ -22,6 +22,8 @@ """ Run synthetic.py for npipes in [1,16], nstages in [1,16] """ +from __future__ import division +from __future__ import unicode_literals import re import sys @@ -49,7 +51,7 @@ def write_shell_script(f, data_filename, description, ncores, gflops, max_pipes_ # We'd like each run of synthetic to take ~10 seconds desired_time_per_run = 10 est_gflops_avail = min(nstages * npipes, ncores) * gflops - nsamples = (est_gflops_avail * desired_time_per_run)/(512.0 * nstages * npipes) + nsamples = (est_gflops_avail * desired_time_per_run) / (512.0 * nstages * npipes) nsamples = int(nsamples * 1e9) cmd = "./synthetic.py -m -s %d -p %d -N %d\n" % (nstages, npipes, nsamples) diff --git a/gnuradio-runtime/examples/mp-sched/synthetic.py b/gnuradio-runtime/examples/mp-sched/synthetic.py index 16e39734ae..0f0b7b37cc 100755..100644 --- a/gnuradio-runtime/examples/mp-sched/synthetic.py +++ b/gnuradio-runtime/examples/mp-sched/synthetic.py @@ -19,6 +19,9 @@ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # +from __future__ import print_function +from __future__ import division +from __future__ import unicode_literals from gnuradio import gr, eng_notation from gnuradio import blocks, filter from gnuradio.eng_arg import eng_float, intx @@ -35,7 +38,7 @@ class pipeline(gr.hier_block2): gr.hier_block2.__init__(self, "pipeline", gr.io_signature(1, 1, gr.sizeof_float), gr.io_signature(0, 0, 0)) - taps = ntaps*[1.0/ntaps] + taps = ntaps*[1.0 / ntaps] upstream = self for i in range(nstages): op = filter.fir_filter_fff(1, taps) @@ -85,23 +88,23 @@ def time_it(tb): start = os.times() tb.run() stop = os.times() - delta = map((lambda a, b: a-b), stop, start) + delta = list(map((lambda a, b: a-b), stop, start)) user, sys, childrens_user, childrens_sys, real = delta total_user = user + childrens_user total_sys = sys + childrens_sys if tb.machine_readable: - print "%3d %3d %.3e %7.3f %7.3f %7.3f %7.3f %.6e %.3e" % ( - tb.npipes, tb.nstages, tb.nsamples, real, total_user, total_sys, (total_user+total_sys)/real, tb.flop, tb.flop/real) + print("%3d %3d %.3e %7.3f %7.3f %7.3f %7.3f %.6e %.3e" % ( + tb.npipes, tb.nstages, tb.nsamples, real, total_user, total_sys, (total_user+total_sys) / real, tb.flop, tb.flop / real)) else: - print "npipes %7d" % (tb.npipes,) - print "nstages %7d" % (tb.nstages,) - print "nsamples %s" % (eng_notation.num_to_str(tb.nsamples),) - print "real %7.3f" % (real,) - print "user %7.3f" % (total_user,) - print "sys %7.3f" % (total_sys,) - print "(user+sys)/real %7.3f" % ((total_user + total_sys)/real,) - print "pseudo_flop %s" % (eng_notation.num_to_str(tb.flop),) - print "pseudo_flop/real %s" % (eng_notation.num_to_str(tb.flop/real),) + print("npipes %7d" % (tb.npipes,)) + print("nstages %7d" % (tb.nstages,)) + print("nsamples %s" % (eng_notation.num_to_str(tb.nsamples),)) + print("real %7.3f" % (real,)) + print("user %7.3f" % (total_user,)) + print("sys %7.3f" % (total_sys,)) + print("(user+sys)/real %7.3f" % ((total_user + total_sys) / real,)) + print("pseudo_flop %s" % (eng_notation.num_to_str(tb.flop),)) + print("pseudo_flop/real %s" % (eng_notation.num_to_str(tb.flop / real),)) if __name__ == "__main__": @@ -109,7 +112,7 @@ if __name__ == "__main__": tb = top() time_it(tb) except KeyboardInterrupt: - raise SystemExit, 128 + raise SystemExit(128) diff --git a/gnuradio-runtime/examples/mp-sched/wfm_rcv_pll_to_wav.py b/gnuradio-runtime/examples/mp-sched/wfm_rcv_pll_to_wav.py index bb3296d428..93f26c6637 100755..100644 --- a/gnuradio-runtime/examples/mp-sched/wfm_rcv_pll_to_wav.py +++ b/gnuradio-runtime/examples/mp-sched/wfm_rcv_pll_to_wav.py @@ -20,6 +20,8 @@ # Boston, MA 02110-1301, USA. # +from __future__ import division +from __future__ import unicode_literals from gnuradio import gr, gru, eng_notation, filter from gnuradio import audio from gnuradio import analog @@ -94,7 +96,7 @@ class wfm_rx_block (gr.top_block): if args.volume is None: g = self.volume_range() - args.volume = float(g[0]+g[1])/2 + args.volume = float(g[0]+g[1]) / 2 # set initial values @@ -109,8 +111,8 @@ class wfm_rx_block (gr.top_block): def set_vol (self, vol): g = self.volume_range() self.vol = max(g[0], min(g[1], vol)) - self.volume_control_l.set_k(10**(self.vol/10)) - self.volume_control_r.set_k(10**(self.vol/10)) + self.volume_control_l.set_k(10**(self.vol / 10)) + self.volume_control_r.set_k(10**(self.vol / 10)) def volume_range(self): return (-20.0, 0.0, 0.5) diff --git a/gnuradio-runtime/examples/network/audio_sink.py b/gnuradio-runtime/examples/network/audio_sink.py index 9b91db5d1e..9ebe8a4c80 100755..100644 --- a/gnuradio-runtime/examples/network/audio_sink.py +++ b/gnuradio-runtime/examples/network/audio_sink.py @@ -20,6 +20,7 @@ # Boston, MA 02110-1301, USA. # +from __future__ import unicode_literals from gnuradio import gr from gnuradio import blocks from argparse import ArgumentParser diff --git a/gnuradio-runtime/examples/network/audio_source.py b/gnuradio-runtime/examples/network/audio_source.py index 6a464a8f28..cc4a34c63f 100755..100644 --- a/gnuradio-runtime/examples/network/audio_source.py +++ b/gnuradio-runtime/examples/network/audio_source.py @@ -20,6 +20,7 @@ # Boston, MA 02110-1301, USA. # +from __future__ import unicode_literals from gnuradio import gr from gnuradio import blocks from argparse import ArgumentParser diff --git a/gnuradio-runtime/examples/network/dial_tone_sink.py b/gnuradio-runtime/examples/network/dial_tone_sink.py index 4b1db98649..e6acbb08d4 100755..100644 --- a/gnuradio-runtime/examples/network/dial_tone_sink.py +++ b/gnuradio-runtime/examples/network/dial_tone_sink.py @@ -20,6 +20,7 @@ # Boston, MA 02110-1301, USA. # +from __future__ import unicode_literals from gnuradio import gr, audio from gnuradio import blocks from argparse import ArgumentParser diff --git a/gnuradio-runtime/examples/network/dial_tone_source.py b/gnuradio-runtime/examples/network/dial_tone_source.py index ee2bc9529b..aa3ab9954f 100755..100644 --- a/gnuradio-runtime/examples/network/dial_tone_source.py +++ b/gnuradio-runtime/examples/network/dial_tone_source.py @@ -20,6 +20,7 @@ # Boston, MA 02110-1301, USA. # +from __future__ import unicode_literals from gnuradio import gr from argparse import ArgumentParser import sys diff --git a/gnuradio-runtime/examples/network/vector_sink.py b/gnuradio-runtime/examples/network/vector_sink.py index 362f631380..a8850d8a01 100755..100644 --- a/gnuradio-runtime/examples/network/vector_sink.py +++ b/gnuradio-runtime/examples/network/vector_sink.py @@ -20,6 +20,7 @@ # Boston, MA 02110-1301, USA. # +from __future__ import unicode_literals from gnuradio import gr from gnuradio import blocks from gnuradio.eng_arg import eng_float, intx diff --git a/gnuradio-runtime/examples/network/vector_source.py b/gnuradio-runtime/examples/network/vector_source.py index be40134bc0..cf8d0000c2 100755..100644 --- a/gnuradio-runtime/examples/network/vector_source.py +++ b/gnuradio-runtime/examples/network/vector_source.py @@ -20,6 +20,7 @@ # Boston, MA 02110-1301, USA. # +from __future__ import unicode_literals from gnuradio import gr from gnuradio import blocks from argparse import ArgumentParser diff --git a/gnuradio-runtime/examples/volk_benchmark/volk_math.py b/gnuradio-runtime/examples/volk_benchmark/volk_math.py index 753257c237..6fc6cfa78d 100755..100644 --- a/gnuradio-runtime/examples/volk_benchmark/volk_math.py +++ b/gnuradio-runtime/examples/volk_benchmark/volk_math.py @@ -1,5 +1,7 @@ #!/usr/bin/env python +from __future__ import print_function +from __future__ import unicode_literals from gnuradio import gr from gnuradio import blocks import argparse @@ -87,7 +89,7 @@ def run_tests(func, N, iters): res = format_results(func.__name__, t) return res except AttributeError: - print "\tCould not run test. Skipping." + print("\tCould not run test. Skipping.") return None def main(): @@ -119,7 +121,7 @@ def main(): default=20, help='Number of iterations [default: %(default)s]') parser.add_argument('--tests', type=int, nargs='*', - choices=xrange(len(avail_tests)), + choices=list(range(len(avail_tests))), help='A list of tests to run; can be a single test or a \ space-separated list.') parser.add_argument('--list', action='store_true', @@ -129,8 +131,8 @@ def main(): args = parser.parse_args() if(args.list): - print "Available Tests to Run:" - print "\n".join(["\t{0}: {1}".format(i,f.__name__) for i,f in enumerate(avail_tests)]) + print("Available Tests to Run:") + print("\n".join(["\t{0}: {1}".format(i,f.__name__) for i,f in enumerate(avail_tests)])) sys.exit(0) N = int(args.nitems) @@ -141,7 +143,7 @@ def main(): new_table(conn, label) if args.all: - tests = xrange(len(avail_tests)) + tests = list(range(len(avail_tests))) else: tests = args.tests diff --git a/gnuradio-runtime/examples/volk_benchmark/volk_plot.py b/gnuradio-runtime/examples/volk_benchmark/volk_plot.py index 48f9922054..2e02773e05 100755..100644 --- a/gnuradio-runtime/examples/volk_benchmark/volk_plot.py +++ b/gnuradio-runtime/examples/volk_benchmark/volk_plot.py @@ -1,5 +1,7 @@ #!/usr/bin/env python +from __future__ import division +from __future__ import unicode_literals import sys, math import argparse from volk_test_funcs import * @@ -100,7 +102,7 @@ def main(): # Plot the results - x0 = xrange(len(name_reg)) + x0 = list(range(len(name_reg))) i = 0 for t in (table_data): ydata = [] @@ -119,7 +121,7 @@ def main(): if(args.percent != t): # makes x values for this data set placement # width of bars depends on number of comparisons - wdth = 0.80/(M-1) + wdth = 0.80 / (M-1) x1 = [x + i*wdth for x in x0] i += 1 @@ -130,7 +132,7 @@ def main(): else: # makes x values for this data set placement # width of bars depends on number of comparisons - wdth = 0.80/M + wdth = 0.80 / M x1 = [x + i*wdth for x in x0] i += 1 diff --git a/gnuradio-runtime/examples/volk_benchmark/volk_test_funcs.py b/gnuradio-runtime/examples/volk_benchmark/volk_test_funcs.py index a7dd7b705c..603c2ae5c3 100644 --- a/gnuradio-runtime/examples/volk_benchmark/volk_test_funcs.py +++ b/gnuradio-runtime/examples/volk_benchmark/volk_test_funcs.py @@ -1,5 +1,7 @@ #!/usr/bin/env python +from __future__ import print_function +from __future__ import unicode_literals from gnuradio import gr from gnuradio import blocks import math, sys, os, time @@ -122,18 +124,18 @@ class helper(gr.top_block): self.snks = [] self.head = blocks.head(isizeof, N) - for n in xrange(nsrcs): + for n in range(nsrcs): self.srcs.append(blocks.null_source(isizeof)) - for n in xrange(nsnks): + for n in range(nsnks): self.snks.append(blocks.null_sink(osizeof)) self.connect(self.srcs[0], self.head, (self.op,0)) - for n in xrange(1, nsrcs): + for n in range(1, nsrcs): self.connect(self.srcs[n], (self.op,n)) - for n in xrange(nsnks): + for n in range(nsnks): self.connect((self.op,n), self.snks[n]) def timeit(tb, iterations): @@ -143,10 +145,10 @@ def timeit(tb, iterations): ''' r = gr.enable_realtime_scheduling() if r != gr.RT_OK: - print "Warning: failed to enable realtime scheduling" + print("Warning: failed to enable realtime scheduling") times = [] - for i in xrange(iterations): + for i in range(iterations): start_time = time.time() tb.run() end_time = time.time() diff --git a/gnuradio-runtime/examples/volk_benchmark/volk_types.py b/gnuradio-runtime/examples/volk_benchmark/volk_types.py index 546e9629c0..697ec213c1 100755..100644 --- a/gnuradio-runtime/examples/volk_benchmark/volk_types.py +++ b/gnuradio-runtime/examples/volk_benchmark/volk_types.py @@ -1,5 +1,7 @@ #!/usr/bin/env python +from __future__ import print_function +from __future__ import unicode_literals from gnuradio import gr from gnuradio import blocks import argparse @@ -105,7 +107,7 @@ def run_tests(func, N, iters): res = format_results(func.__name__, t) return res except AttributeError: - print "\tCould not run test. Skipping." + print("\tCould not run test. Skipping.") return None def main(): @@ -143,7 +145,7 @@ def main(): default=20, help='Number of iterations [default: %(default)s]') parser.add_argument('--tests', type=int, nargs='*', - choices=xrange(len(avail_tests)), + choices=list(range(len(avail_tests))), help='A list of tests to run; can be a single test or a \ space-separated list.') parser.add_argument('--list', action='store_true', @@ -153,8 +155,8 @@ def main(): args = parser.parse_args() if(args.list): - print "Available Tests to Run:" - print "\n".join(["\t{0}: {1}".format(i,f.__name__) for i,f in enumerate(avail_tests)]) + print("Available Tests to Run:") + print("\n".join(["\t{0}: {1}".format(i,f.__name__) for i,f in enumerate(avail_tests)])) sys.exit(0) N = int(args.nitems) @@ -165,7 +167,7 @@ def main(): new_table(conn, label) if args.all: - tests = xrange(len(avail_tests)) + tests = list(range(len(avail_tests))) else: tests = args.tests diff --git a/gnuradio-runtime/include/gnuradio/sptr_magic.h b/gnuradio-runtime/include/gnuradio/sptr_magic.h index 6deb3062ae..d5e587186a 100644 --- a/gnuradio-runtime/include/gnuradio/sptr_magic.h +++ b/gnuradio-runtime/include/gnuradio/sptr_magic.h @@ -40,7 +40,7 @@ namespace gnuradio { static void create_and_stash_initial_sptr(gr::hier_block2 *p); static void cancel_initial_sptr(gr::hier_block2 *p); }; - }; + } /* * \brief New! Improved! Standard method to get/create the diff --git a/gnuradio-runtime/lib/CMakeLists.txt b/gnuradio-runtime/lib/CMakeLists.txt index 5e414164f8..4fd5a610f6 100644 --- a/gnuradio-runtime/lib/CMakeLists.txt +++ b/gnuradio-runtime/lib/CMakeLists.txt @@ -24,7 +24,7 @@ GR_CHECK_HDR_N_DEF(sys/resource.h HAVE_SYS_RESOURCE_H) # Handle the generated constants ######################################################################## execute_process(COMMAND ${PYTHON_EXECUTABLE} -c - "import time;print time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime())" + "import time;print(time.strftime('%a, %d %b %Y %H:%M:%S', time.gmtime()))" OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE ) message(STATUS "Loading build date ${BUILD_DATE} into constants...") @@ -48,8 +48,8 @@ list(APPEND gnuradio_runtime_sources ${CMAKE_CURRENT_BINARY_DIR}/constants.cc) ######################################################################## include_directories(${GNURADIO_RUNTIME_INCLUDE_DIRS} ${CMAKE_CURRENT_SOURCE_DIR} - ${CMAKE_CURRENT_BINARY_DIR}/../include/ - ${VOLK_INCLUDE_DIRS} + ${CMAKE_CURRENT_BINARY_DIR}/../include/ + ${VOLK_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ) diff --git a/gnuradio-runtime/lib/math/gen_sine_table.py b/gnuradio-runtime/lib/math/gen_sine_table.py index d7d11eff11..75e3a0c58f 100755..100644 --- a/gnuradio-runtime/lib/math/gen_sine_table.py +++ b/gnuradio-runtime/lib/math/gen_sine_table.py @@ -20,6 +20,8 @@ # Boston, MA 02110-1301, USA. # +from __future__ import division +from __future__ import unicode_literals import math import sys @@ -38,8 +40,8 @@ def gen_approx_table (f, nentries, min_x, max_x): for i in range (nentries): a = (i * incx) + min_x b = ((i + 1) * incx) + min_x - m = (f(b)-f(a))/(b-a) - c = (3*a+b)*(f(a)-f(b))/(4*(b-a)) + (f((a+b)/2) + f(a))/2 + m = (f(b)-f(a)) / (b-a) + c = (3*a+b)*(f(a)-f(b))/(4*(b-a)) + (f(old_div((a+b) / 2) + f(a)),2) abs_error = c+m*a-f(a) r.append ((m, c, abs_error)) return r diff --git a/gnuradio-runtime/lib/pmt/CMakeLists.txt b/gnuradio-runtime/lib/pmt/CMakeLists.txt index e5c8f2f47e..85b2a4d6e0 100644 --- a/gnuradio-runtime/lib/pmt/CMakeLists.txt +++ b/gnuradio-runtime/lib/pmt/CMakeLists.txt @@ -66,7 +66,7 @@ add_custom_command( ${CMAKE_CURRENT_SOURCE_DIR}/unv_template.h.t ${CMAKE_CURRENT_SOURCE_DIR}/unv_template.cc.t ${CMAKE_CURRENT_SOURCE_DIR}/unv_qa_template.cc.t - COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B} -c + COMMAND ${PYTHON_EXECUTABLE} -B -c "import os, sys; srcdir='${CMAKE_CURRENT_SOURCE_DIR}'; sys.path.append(srcdir); os.environ['srcdir']=srcdir; from generate_unv import main; main()" WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} VERBATIM diff --git a/gnuradio-runtime/lib/pmt/gen-serial-tags.py b/gnuradio-runtime/lib/pmt/gen-serial-tags.py index 18e927beb5..2ff2240a47 100644 --- a/gnuradio-runtime/lib/pmt/gen-serial-tags.py +++ b/gnuradio-runtime/lib/pmt/gen-serial-tags.py @@ -32,11 +32,14 @@ enum pst_tags { #endif /* INCLUDED_PMT_SERIAL_TAGS_H */ """ +from __future__ import print_function +from __future__ import unicode_literals + import sys, os, re if __name__ == '__main__': if len(sys.argv) != 3: - print "Usage %s <input_scm_file> <output_hdr_file>"%__file__ + print("Usage %s <input_scm_file> <output_hdr_file>"%__file__) exit() input_scm_file, output_hdr_file = sys.argv[1:] enums = list() diff --git a/gnuradio-runtime/lib/pmt/generate_unv.py b/gnuradio-runtime/lib/pmt/generate_unv.py index 6218099fc1..45c57a3fb8 100755..100644 --- a/gnuradio-runtime/lib/pmt/generate_unv.py +++ b/gnuradio-runtime/lib/pmt/generate_unv.py @@ -23,6 +23,7 @@ """ Generate code for uniform numeric vectors """ +from __future__ import unicode_literals import re, os, os.path @@ -93,7 +94,7 @@ using namespace pmt; # set srcdir to the directory that contains Makefile.am try: srcdir = os.environ['srcdir'] -except KeyError, e: +except KeyError as e: srcdir = "." srcdir = srcdir + '/' diff --git a/gnuradio-runtime/lib/sptr_magic.cc b/gnuradio-runtime/lib/sptr_magic.cc index e5e83722fc..bffef04756 100644 --- a/gnuradio-runtime/lib/sptr_magic.cc +++ b/gnuradio-runtime/lib/sptr_magic.cc @@ -102,4 +102,4 @@ namespace gnuradio { s_map.erase(pos); return sptr; } -}; +} diff --git a/gnuradio-runtime/python/build_utils.py b/gnuradio-runtime/python/build_utils.py index cf58a97637..82a2265cc2 100644 --- a/gnuradio-runtime/python/build_utils.py +++ b/gnuradio-runtime/python/build_utils.py @@ -21,6 +21,7 @@ """Misc utilities used at build time """ +from __future__ import unicode_literals import re, os, os.path from build_utils_codes import * @@ -29,7 +30,7 @@ from build_utils_codes import * # set srcdir to the directory that contains Makefile.am try: srcdir = os.environ['srcdir'] -except KeyError, e: +except KeyError as e: srcdir = "." srcdir = srcdir + '/' @@ -39,7 +40,7 @@ try: do_makefile = False else: do_makefile = True -except KeyError, e: +except KeyError as e: do_makefile = False # set do_sources to either true or false dependeing on the environment @@ -48,7 +49,7 @@ try: do_sources = False else: do_sources = True -except KeyError, e: +except KeyError as e: do_sources = True name_dict = {} @@ -127,7 +128,7 @@ def extract_extension (template_name): # we return everything between the penultimate . and .t mo = re.search (r'\.([a-z]+)\.t$', template_name) if not mo: - raise ValueError, "Incorrectly formed template_name '%s'" % (template_name,) + raise ValueError("Incorrectly formed template_name '%s'" % (template_name,)) return mo.group (1) def open_src (name, mode): diff --git a/gnuradio-runtime/python/build_utils_codes.py b/gnuradio-runtime/python/build_utils_codes.py index 9ea96baae4..22a6bdb99b 100644 --- a/gnuradio-runtime/python/build_utils_codes.py +++ b/gnuradio-runtime/python/build_utils_codes.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals # # Copyright 2004 Free Software Foundation, Inc. # diff --git a/gnuradio-runtime/python/gnuradio/__init__.py b/gnuradio-runtime/python/gnuradio/__init__.py index 062450cb5f..c1735c3d8b 100644 --- a/gnuradio-runtime/python/gnuradio/__init__.py +++ b/gnuradio-runtime/python/gnuradio/__init__.py @@ -7,6 +7,7 @@ While not primarily a simulation tool, GNU Radio does support development of sig GNU Radio is licensed under the GNU General Public License (GPL) version 3. All of the code is copyright of the Free Software Foundation. """ +from __future__ import unicode_literals # This file makes gnuradio a package # The docstring will be associated with the top level of the package. diff --git a/gnuradio-runtime/python/gnuradio/ctrlport/GNURadioControlPortClient.py b/gnuradio-runtime/python/gnuradio/ctrlport/GNURadioControlPortClient.py index 87d2cf5658..beec500023 100644 --- a/gnuradio-runtime/python/gnuradio/ctrlport/GNURadioControlPortClient.py +++ b/gnuradio-runtime/python/gnuradio/ctrlport/GNURadioControlPortClient.py @@ -27,6 +27,8 @@ Remote Procedure Call (RPC) transports, the Apache Thrift middle-ware RPC is currently the only supported transport. """ +from __future__ import print_function +from __future__ import unicode_literals import exceptions @@ -38,7 +40,7 @@ Two constructors are provided for creating a connection to ControlPort. """ -class GNURadioControlPortClient(): +class GNURadioControlPortClient(object): """ Constructor for creating a ControlPort connection to a specified host / port @@ -113,7 +115,7 @@ class GNURadioControlPortClient(): self.client = None from gnuradio.ctrlport.RPCConnection import RPCMethods - if RPCMethods.has_key(rpcmethod): + if rpcmethod in RPCMethods: from gnuradio.ctrlport.RPCConnectionThrift import RPCConnectionThrift if rpcmethod == 'thrift': #print("making RPCConnectionThrift") @@ -128,5 +130,5 @@ class GNURadioControlPortClient(): if not blockingcallback is None: blockingcallback() else: - print("Unsupported RPC method: ", rpcmethod) + print(("Unsupported RPC method: ", rpcmethod)) raise exceptions.ValueError() diff --git a/gnuradio-runtime/python/gnuradio/ctrlport/GrDataPlotter.py b/gnuradio-runtime/python/gnuradio/ctrlport/GrDataPlotter.py index e0499c5eba..cb66baebb9 100644 --- a/gnuradio-runtime/python/gnuradio/ctrlport/GrDataPlotter.py +++ b/gnuradio-runtime/python/gnuradio/ctrlport/GrDataPlotter.py @@ -20,6 +20,9 @@ # Boston, MA 02110-1301, USA. # +from __future__ import print_function +from __future__ import unicode_literals + from gnuradio import gr from gnuradio import blocks from gnuradio import filter @@ -31,7 +34,7 @@ try: from PyQt4 import QtGui, QtCore import sip except ImportError: - print "Error: Program requires PyQt4 and gr-qtgui." + print("Error: Program requires PyQt4 and gr-qtgui.") sys.exit(1) class GrDataPlotParent(gr.top_block, QtGui.QWidget): @@ -62,7 +65,7 @@ class GrDataPlotParent(gr.top_block, QtGui.QWidget): self.layout.removeWidget(self.py_window) self.disconnect(self.thr, (self.snk, 0)) self.disconnect(self.src[0], self.thr) - for n in xrange(1, self._ncons): + for n in range(1, self._ncons): self.disconnect(self.src[n], (self.snk,n)) self._ncons = nconnections @@ -75,7 +78,7 @@ class GrDataPlotParent(gr.top_block, QtGui.QWidget): self._last_data = [] self.src = [] - for n in xrange(self._ncons): + for n in range(self._ncons): self.set_line_label(n, self.knobnames[n]) self._last_data.append(int(self._npts)*[0,]) @@ -142,7 +145,7 @@ class GrDataPlotParent(gr.top_block, QtGui.QWidget): if(self._npts != npts): # Adjust buffers to accommodate new settings - for n in xrange(self._ncons): + for n in range(self._ncons): if(npts < self._npts): if(self._data_len[n] < npts): self._last_data[n] = self._last_data[n][0:npts] @@ -156,7 +159,7 @@ class GrDataPlotParent(gr.top_block, QtGui.QWidget): if(self._stripchart): # Update the plot data depending on type - for n in xrange(self._ncons): + for n in range(self._ncons): if(type(data[n]) == list): data[n] = self.data_to_complex(data[n]) if(len(data[n]) > self._npts): @@ -179,7 +182,7 @@ class GrDataPlotParent(gr.top_block, QtGui.QWidget): self._last_data[n].append(data[n]) self.src[n].set_data(self._last_data[n]) else: - for n in xrange(self._ncons): + for n in range(self._ncons): if(type(data[n]) != list): data[n] = [data[n],] data[n] = self.data_to_complex(data[n]) @@ -407,11 +410,11 @@ class GrTimeRasterB(GrDataPlotParent): self.snk.set_line_label(n, self.knobnames[n]) -class GrDataPlotterValueTable: +class GrDataPlotterValueTable(object): def __init__(self, uid, parent, x, y, xsize, ysize, headers=['Statistic Key ( Source Block :: Stat Name ) ', 'Curent Value', 'Units', 'Description']): - # must encapsulate, cuz Qt's bases are not classes + # must encapsulate, cuz Qt's bases are not classes self.uid = uid self.treeWidget = QtGui.QTreeWidget(parent) self.treeWidget.setColumnCount(len(headers)) @@ -434,7 +437,7 @@ class GrDataPlotterValueTable: # itemKey is the text in the first column of a QTreeWidgetItem itemKey = str(item.text(0)) - if itemKey in knobs.keys(): + if itemKey in list(knobs.keys()): # This key was found in the tree, update its values. foundKeys.append(itemKey) @@ -465,7 +468,7 @@ class GrDataPlotterValueTable: deleteKeys.append(itemKey) # Add items to tree that are not currently in the tree. - for k in knobs.keys(): + for k in list(knobs.keys()): if k not in foundKeys: v = knobs[k].value if(type(v) == ControlPort.complex): diff --git a/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnection.py b/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnection.py index 1b129534c9..b85c827f72 100644 --- a/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnection.py +++ b/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnection.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals # # Copyright 2015 Free Software Foundation, Inc. # diff --git a/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnectionThrift.py b/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnectionThrift.py index 522c74117b..466fc9fc04 100644 --- a/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnectionThrift.py +++ b/gnuradio-runtime/python/gnuradio/ctrlport/RPCConnectionThrift.py @@ -20,6 +20,7 @@ # Boston, MA 02110-1301, USA. # +from __future__ import unicode_literals from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport @@ -30,7 +31,7 @@ from gnuradio import gr import pmt import sys -class ThriftRadioClient: +class ThriftRadioClient(object): def __init__(self, host, port): self.tsocket = TSocket.TSocket(host, port) self.transport = TTransport.TBufferedTransport(self.tsocket) @@ -55,7 +56,7 @@ Args: """ class RPCConnectionThrift(RPCConnection.RPCConnection): - class Knob(): + class Knob(object): def __init__(self, key, value=None, ktype=0): (self.key, self.value, self.ktype) = (key, value, ktype) @@ -144,7 +145,7 @@ class RPCConnectionThrift(RPCConnection.RPCConnection): def properties(self, *args): knobprops = self.thriftclient.radio.properties(*args) - for key, knobprop in knobprops.iteritems(): + for key, knobprop in list(knobprops.items()): #print("key:", key, "value:", knobprop, "type:", knobprop.type) knobprops[key].min = self.unpackKnob(key, knobprop.min) knobprops[key].max = self.unpackKnob(key, knobprop.max) @@ -153,28 +154,28 @@ class RPCConnectionThrift(RPCConnection.RPCConnection): def getKnobs(self, *args): result = {} - for key, knob in self.thriftclient.radio.getKnobs(*args).iteritems(): + for key, knob in list(self.thriftclient.radio.getKnobs(*args).items()): #print("key:", key, "value:", knob, "type:", knob.type) result[key] = self.unpackKnob(key, knob) # If complex, convert to Python complex # FIXME: better list iterator way to handle this? if(knob.type == self.BaseTypes.C32VECTOR): - for i in xrange(len(result[key].value)): + for i in range(len(result[key].value)): result[key].value[i] = complex(result[key].value[i].re, result[key].value[i].im) return result def getKnobsRaw(self, *args): result = {} - for key, knob in self.thriftclient.radio.getKnobs(*args).iteritems(): + for key, knob in list(self.thriftclient.radio.getKnobs(*args).items()): #print("key:", key, "value:", knob, "type:", knob.type) result[key] = knob return result def getRe(self,*args): result = {} - for key, knob in self.thriftclient.radio.getRe(*args).iteritems(): + for key, knob in list(self.thriftclient.radio.getRe(*args).items()): result[key] = self.unpackKnob(key, knob) return result @@ -182,7 +183,7 @@ class RPCConnectionThrift(RPCConnection.RPCConnection): if(type(*args) == dict): a = dict(*args) result = {} - for key, knob in a.iteritems(): + for key, knob in list(a.items()): result[key] = self.packKnob(knob) self.thriftclient.radio.setKnobs(result) elif(type(*args) == list or type(*args) == tuple): diff --git a/gnuradio-runtime/python/gnuradio/ctrlport/__init__.py b/gnuradio-runtime/python/gnuradio/ctrlport/__init__.py index 8f33d65bbc..363d42a68e 100644 --- a/gnuradio-runtime/python/gnuradio/ctrlport/__init__.py +++ b/gnuradio-runtime/python/gnuradio/ctrlport/__init__.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import +from __future__ import unicode_literals # # Copyright 2012 Free Software Foundation, Inc. # @@ -22,7 +24,7 @@ # import swig generated symbols into the ctrlport namespace #from ctrlport_swig import * -from monitor import * +from .monitor import * # import any pure python here #import GNURadio diff --git a/gnuradio-runtime/python/gnuradio/ctrlport/gr-perf-monitorx b/gnuradio-runtime/python/gnuradio/ctrlport/gr-perf-monitorx index 15a2153a0f..302275feb1 100644 --- a/gnuradio-runtime/python/gnuradio/ctrlport/gr-perf-monitorx +++ b/gnuradio-runtime/python/gnuradio/ctrlport/gr-perf-monitorx @@ -20,6 +20,8 @@ # Boston, MA 02110-1301, USA. # +from __future__ import print_function + import sys, time, re, pprint import random,math,operator try: @@ -36,14 +38,14 @@ try: try: from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar except ImportError: - print sys.argv[0], "could not load QTAgg backend." + print(sys.argv[0], "could not load QTAgg backend.") sys.exit(1) from matplotlib.figure import Figure except ImportError: - print sys.argv[0], "requires networkx and matplotlib.", \ - "Please check that they are installed and try again." + print(sys.argv[0], "requires networkx and matplotlib.", + "Please check that they are installed and try again.") sys.exit(1) from PyQt4 import QtCore,Qt @@ -282,7 +284,7 @@ class ConInfoDialog(QtGui.QDialog): class DataTable(QtGui.QWidget): def update(self): - print "update" + print("update") def closeEvent(self, event): self.timer = None @@ -498,7 +500,7 @@ class MForm(QtGui.QWidget): self.clockSel.setCurrentIndex(self.clockSelIdx) self.prevent_clock_change = False except: - print "WARNING: Failed to get current clock setting!" + print("WARNING: Failed to get current clock setting!") nodes_stream = self.G_stream.nodes() nodes_msg = self.G_msg.nodes() @@ -571,7 +573,7 @@ class MForm(QtGui.QWidget): self.parent.statusBar().showMessage("Current GNU Radio Control Port Query Latency: %f ms"%\ (latency*1000)) - except Exception, e: + except Exception as e: sys.stderr.write("gr-perf-monitorx: radio.getKnobs threw exception ({0}).\n".format(e)) if(type(self.parent) is MAINWindow): # Find window of connection @@ -625,7 +627,7 @@ class MForm(QtGui.QWidget): return; idx = self.clockSel.currentIndex(); clk = self.clocks.values()[idx] -# print "UPDATE CLOCK!!! %d -> %d"%(idx,clk); +# print("UPDATE CLOCK!!! %d -> %d"%(idx,clk);) k = self.radioclient.getKnobs([self.clockKey]); k[self.clockKey].value = clk; km = {}; diff --git a/gnuradio-runtime/python/gnuradio/ctrlport/monitor.py b/gnuradio-runtime/python/gnuradio/ctrlport/monitor.py index f651be2449..49b66e9830 100644 --- a/gnuradio-runtime/python/gnuradio/ctrlport/monitor.py +++ b/gnuradio-runtime/python/gnuradio/ctrlport/monitor.py @@ -20,12 +20,15 @@ # Boston, MA 02110-1301, USA. # +from __future__ import print_function +from __future__ import unicode_literals + import sys, subprocess, re, signal, time, atexit, os from gnuradio import gr -class monitor: +class monitor(object): def __init__(self,tool="gr-ctrlport-monitor"): - print "ControlPort Monitor running." + print("ControlPort Monitor running.") self.started = False self.tool = tool atexit.register(self.shutdown) @@ -38,35 +41,35 @@ class monitor: gr.prefs().singleton().set_bool("PerfCounters","on",True); gr.prefs().singleton().set_bool("PerfCounters","export",True); except: - print "no support for gr.prefs setting" + print("no support for gr.prefs setting") def __del__(self): if(self.started): self.stop() def start(self): - print "monitor::endpoints() = %s" % (gr.rpcmanager_get().endpoints()) + print("monitor::endpoints() = %s" % (gr.rpcmanager_get().endpoints())) try: cmd = map(lambda a: [self.tool, re.search("-h (\S+|\d+\.\d+\.\d+\.\d+)",a).group(1), re.search("-p (\d+)",a).group(1)], gr.rpcmanager_get().endpoints())[0] - print "running: %s"%(str(cmd)) + print("running: %s"%(str(cmd))) self.proc = subprocess.Popen(cmd); self.started = True except: self.proc = None - print "failed to to start ControlPort Monitor on specified port" + print("failed to to start ControlPort Monitor on specified port") def stop(self): if(self.proc): if(self.proc.returncode == None): - print "\tcalling stop on shutdown" + print("\tcalling stop on shutdown") self.proc.terminate() else: - print "\tno proc to shut down, exiting" + print("\tno proc to shut down, exiting") def shutdown(self): - print "ctrlport.monitor received shutdown signal" + print("ctrlport.monitor received shutdown signal") if(self.started): self.stop() diff --git a/gnuradio-runtime/python/gnuradio/eng_arg.py b/gnuradio-runtime/python/gnuradio/eng_arg.py index 05cd8a1f2a..5983352443 100644 --- a/gnuradio-runtime/python/gnuradio/eng_arg.py +++ b/gnuradio-runtime/python/gnuradio/eng_arg.py @@ -22,6 +22,7 @@ ''' Add support for engineering notation to argparse.ArgumentParser ''' +from __future__ import unicode_literals import argparse from gnuradio import eng_notation diff --git a/gnuradio-runtime/python/gnuradio/eng_notation.py b/gnuradio-runtime/python/gnuradio/eng_notation.py index d23f9005f0..5a3a216ee4 100644 --- a/gnuradio-runtime/python/gnuradio/eng_notation.py +++ b/gnuradio-runtime/python/gnuradio/eng_notation.py @@ -21,6 +21,7 @@ """ Display numbers as strings using engineering notation. """ +from __future__ import unicode_literals scale_factor = {} scale_factor['E'] = 1e18 @@ -66,7 +67,7 @@ def str_to_num (value): try: scale = 1.0 suffix = value[-1] - if scale_factor.has_key (suffix): + if suffix in scale_factor: return float (value[0:-1]) * scale_factor[suffix] return float (value) except: diff --git a/gnuradio-runtime/python/gnuradio/eng_option.py b/gnuradio-runtime/python/gnuradio/eng_option.py index ae000fe442..565780be28 100644 --- a/gnuradio-runtime/python/gnuradio/eng_option.py +++ b/gnuradio-runtime/python/gnuradio/eng_option.py @@ -20,10 +20,12 @@ # '''Add support for engineering notation to optparse.OptionParser''' +from __future__ import absolute_import +from __future__ import unicode_literals from copy import copy from optparse import Option, OptionValueError -import eng_notation +from . import eng_notation def check_eng_float (option, opt, value): try: diff --git a/gnuradio-runtime/python/gnuradio/gr/CMakeLists.txt b/gnuradio-runtime/python/gnuradio/gr/CMakeLists.txt index fc966b8ece..7c82b1df35 100644 --- a/gnuradio-runtime/python/gnuradio/gr/CMakeLists.txt +++ b/gnuradio-runtime/python/gnuradio/gr/CMakeLists.txt @@ -22,6 +22,7 @@ include(GrPython) GR_PYTHON_INSTALL(FILES __init__.py + exceptions.py tag_utils.py packet_utils.py gateway.py @@ -48,6 +49,6 @@ if(ENABLE_TESTING) file(GLOB py_qa_test_files "qa_*.py") foreach(py_qa_test_file ${py_qa_test_files}) get_filename_component(py_qa_test_name ${py_qa_test_file} NAME_WE) - GR_ADD_TEST(${py_qa_test_name} ${QA_PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) + GR_ADD_TEST(${py_qa_test_name} ${QA_PYTHON_EXECUTABLE} -B ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) diff --git a/gnuradio-runtime/python/gnuradio/gr/__init__.py b/gnuradio-runtime/python/gnuradio/gr/__init__.py index 9717390e3e..72f54e9f42 100644 --- a/gnuradio-runtime/python/gnuradio/gr/__init__.py +++ b/gnuradio-runtime/python/gnuradio/gr/__init__.py @@ -24,6 +24,8 @@ """ Core contents. """ +from __future__ import absolute_import +from __future__ import unicode_literals # This is the main GNU Radio python module. # We pull the swig output and the other modules into the gnuradio.gr namespace @@ -31,20 +33,20 @@ Core contents. # If gnuradio is installed then the swig output will be in this directory. # Otherwise it will reside in ../../../swig. -import os +import os, sys try: - from runtime_swig import * + from .runtime_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "..", "swig")) - from runtime_swig import * + from .runtime_swig import * -from exceptions import * -from top_block import * -from hier_block2 import * -from tag_utils import * -from gateway import basic_block, sync_block, decim_block, interp_block +from .exceptions import * +from .top_block import * +from .hier_block2 import * +from .tag_utils import * +from .gateway import basic_block, sync_block, decim_block, interp_block # Force the preference database to be initialized prefs = prefs.singleton diff --git a/gnuradio-runtime/python/gnuradio/gr/exceptions.py b/gnuradio-runtime/python/gnuradio/gr/exceptions.py index dba04750bc..1b7fd025b7 100644 --- a/gnuradio-runtime/python/gnuradio/gr/exceptions.py +++ b/gnuradio-runtime/python/gnuradio/gr/exceptions.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals # # Copyright 2004 Free Software Foundation, Inc. # diff --git a/gnuradio-runtime/python/gnuradio/gr/gateway.py b/gnuradio-runtime/python/gnuradio/gr/gateway.py index 8403421dd5..1acf900f84 100644 --- a/gnuradio-runtime/python/gnuradio/gr/gateway.py +++ b/gnuradio-runtime/python/gnuradio/gr/gateway.py @@ -19,18 +19,23 @@ # Boston, MA 02110-1301, USA. # -import runtime_swig as gr -from runtime_swig import io_signature, io_signaturev -from runtime_swig import block_gw_message_type -from runtime_swig import block_gateway +from __future__ import print_function +from __future__ import unicode_literals + + import numpy +from . import runtime_swig as gr +from .runtime_swig import io_signature, io_signaturev +from .runtime_swig import block_gw_message_type +from .runtime_swig import block_gateway + ######################################################################## # Magic to turn pointers into numpy arrays # http://docs.scipy.org/doc/numpy/reference/arrays.interface.html ######################################################################## def pointer_to_ndarray(addr, dtype, nitems): - class array_like: + class array_like(object): __array_interface__ = { 'data' : (int(addr), False), 'typestr' : dtype.base.str, @@ -87,13 +92,13 @@ class gateway_block(object): #ensure that the sigs are iterable dtypes def sig_to_dtype_sig(sig): if sig is None: sig = () - return map(numpy.dtype, sig) + return list(map(numpy.dtype, sig)) self.__in_sig = sig_to_dtype_sig(in_sig) self.__out_sig = sig_to_dtype_sig(out_sig) #cache the ranges to iterate when dispatching work - self.__in_indexes = range(len(self.__in_sig)) - self.__out_indexes = range(len(self.__out_sig)) + self.__in_indexes = list(range(len(self.__in_sig))) + self.__out_indexes = list(range(len(self.__out_sig))) #convert the signatures into gr.io_signatures def sig_to_gr_io_sigv(sig): diff --git a/gnuradio-runtime/python/gnuradio/gr/gr_threading.py b/gnuradio-runtime/python/gnuradio/gr/gr_threading.py index 5d6f0fdaf9..cb0519f6f6 100644 --- a/gnuradio-runtime/python/gnuradio/gr/gr_threading.py +++ b/gnuradio-runtime/python/gnuradio/gr/gr_threading.py @@ -1,3 +1,5 @@ +from __future__ import absolute_import +from __future__ import unicode_literals # # Copyright 2005 Free Software Foundation, Inc. # @@ -25,10 +27,10 @@ from sys import version_info as _version_info if _version_info[0:2] == (2, 3): #print "Importing gr_threading_23" - from gr_threading_23 import * + from .gr_threading_23 import * elif _version_info[0:2] == (2, 4): #print "Importing gr_threading_24" - from gr_threading_24 import * + from .gr_threading_24 import * else: # assume the patch was applied... #print "Importing system provided threading" diff --git a/gnuradio-runtime/python/gnuradio/gr/gr_threading_23.py b/gnuradio-runtime/python/gnuradio/gr/gr_threading_23.py index 795c1593d4..f4f062f715 100644 --- a/gnuradio-runtime/python/gnuradio/gr/gr_threading_23.py +++ b/gnuradio-runtime/python/gnuradio/gr/gr_threading_23.py @@ -4,15 +4,18 @@ # It's been patched to fix a problem with join, where a KeyboardInterrupt # caused a lock to be left in the acquired state. +from __future__ import print_function +from __future__ import unicode_literals + import sys as _sys try: - import thread + import _thread except ImportError: del _sys.modules[__name__] raise -from StringIO import StringIO as _StringIO +from io import StringIO as _StringIO from time import time as _time, sleep as _sleep from traceback import print_exc as _print_exc @@ -21,11 +24,11 @@ __all__ = ['activeCount', 'Condition', 'currentThread', 'enumerate', 'Event', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Timer', 'setprofile', 'settrace'] -_start_new_thread = thread.start_new_thread -_allocate_lock = thread.allocate_lock -_get_ident = thread.get_ident -ThreadError = thread.error -del thread +_start_new_thread = _thread.start_new_thread +_allocate_lock = _thread.allocate_lock +_get_ident = _thread.get_ident +ThreadError = _thread.error +del _thread # Debug support (adapted from ihooks.py). @@ -127,8 +130,9 @@ class _RLock(_Verbose): # Internal methods used by condition variables - def _acquire_restore(self, (count, owner)): + def _acquire_restore(self, lock): self.__block.acquire() + count, owner = lock self.__count = count self.__owner = owner if __debug__: @@ -313,7 +317,7 @@ class _BoundedSemaphore(_Semaphore): def release(self): if self._Semaphore__value >= self._initial_value: - raise ValueError, "Semaphore released too many times" + raise ValueError("Semaphore released too many times") return _Semaphore.release(self) @@ -627,7 +631,7 @@ def activeCount(): def enumerate(): _active_limbo_lock.acquire() - active = _active.values() + _limbo.values() + active = list(_active.values()) + list(_limbo.values()) _active_limbo_lock.release() return active @@ -698,7 +702,7 @@ def _test(): def run(self): while self.count > 0: item = self.queue.get() - print item + print(item) self.count = self.count - 1 NP = 3 diff --git a/gnuradio-runtime/python/gnuradio/gr/gr_threading_24.py b/gnuradio-runtime/python/gnuradio/gr/gr_threading_24.py index 8ad880b090..6dddce7e22 100644 --- a/gnuradio-runtime/python/gnuradio/gr/gr_threading_24.py +++ b/gnuradio-runtime/python/gnuradio/gr/gr_threading_24.py @@ -4,10 +4,13 @@ # It's been patched to fix a problem with join, where a KeyboardInterrupt # caused a lock to be left in the acquired state. +from __future__ import print_function +from __future__ import unicode_literals + import sys as _sys try: - import thread + import _thread except ImportError: del _sys.modules[__name__] raise @@ -21,11 +24,11 @@ __all__ = ['activeCount', 'Condition', 'currentThread', 'enumerate', 'Event', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Timer', 'setprofile', 'settrace', 'local'] -_start_new_thread = thread.start_new_thread -_allocate_lock = thread.allocate_lock -_get_ident = thread.get_ident -ThreadError = thread.error -del thread +_start_new_thread = _thread.start_new_thread +_allocate_lock = _thread.allocate_lock +_get_ident = _thread.get_ident +ThreadError = _thread.error +del _thread # Debug support (adapted from ihooks.py). @@ -127,8 +130,9 @@ class _RLock(_Verbose): # Internal methods used by condition variables - def _acquire_restore(self, (count, owner)): + def _acquire_restore(self, lock): self.__block.acquire() + count, owner = lock self.__count = count self.__owner = owner if __debug__: @@ -311,7 +315,7 @@ class _BoundedSemaphore(_Semaphore): def release(self): if self._Semaphore__value >= self._initial_value: - raise ValueError, "Semaphore released too many times" + raise ValueError("Semaphore released too many times") return _Semaphore.release(self) @@ -688,7 +692,7 @@ def activeCount(): def enumerate(): _active_limbo_lock.acquire() - active = _active.values() + _limbo.values() + active = list(_active.values()) + list(_limbo.values()) _active_limbo_lock.release() return active @@ -700,7 +704,7 @@ _MainThread() # module, or from the python fallback try: - from thread import _local as local + from _thread import _local as local except ImportError: from _threading_local import local @@ -767,7 +771,7 @@ def _test(): def run(self): while self.count > 0: item = self.queue.get() - print item + print(item) self.count = self.count - 1 NP = 3 diff --git a/gnuradio-runtime/python/gnuradio/gr/hier_block2.py b/gnuradio-runtime/python/gnuradio/gr/hier_block2.py index 3f4c6aa9c7..8d0533c71c 100644 --- a/gnuradio-runtime/python/gnuradio/gr/hier_block2.py +++ b/gnuradio-runtime/python/gnuradio/gr/hier_block2.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals # # Copyright 2006,2007,2014 Free Software Foundation, Inc. # @@ -21,7 +22,7 @@ import functools -from runtime_swig import hier_block2_swig, dot_graph +from .runtime_swig import hier_block2_swig, dot_graph import pmt diff --git a/gnuradio-runtime/python/gnuradio/gr/packet_utils.py b/gnuradio-runtime/python/gnuradio/gr/packet_utils.py index 720cfd962f..770a5c0b36 100644 --- a/gnuradio-runtime/python/gnuradio/gr/packet_utils.py +++ b/gnuradio-runtime/python/gnuradio/gr/packet_utils.py @@ -20,6 +20,9 @@ # Boston, MA 02110-1301, USA. # +from __future__ import print_function +from __future__ import division +from __future__ import unicode_literals from gnuradio import gr import pmt @@ -28,9 +31,9 @@ def make_lengthtags(lengths, offsets, tagname='length', vlen=1): assert(len(offsets) == len(lengths)) for offset, length in zip(offsets, lengths): tag = gr.tag_t() - tag.offset = offset/vlen + tag.offset = offset // vlen tag.key = pmt.string_to_symbol(tagname) - tag.value = pmt.from_long(length/vlen) + tag.value = pmt.from_long(length // vlen) tags.append(tag) return tags @@ -73,7 +76,7 @@ def count_bursts(data, tags, tsb_tag_key, vlen=1): if pos in lengths: if in_packet: print("Got tag at pos {0} current packet_pos is {1}".format(pos, packet_pos)) - raise StandardError("Received packet tag while in packet.") + raise Exception("Received packet tag while in packet.") packet_pos = -1 packet_length = lengths[pos] in_packet = True @@ -128,9 +131,9 @@ def packets_to_vectors(packets, tsb_tag_key, vlen=1): for packet in packets: data.extend(packet) tag = gr.tag_t() - tag.offset = offset/vlen + tag.offset = offset // vlen tag.key = pmt.string_to_symbol(tsb_tag_key) - tag.value = pmt.from_long(len(packet)/vlen) + tag.value = pmt.from_long(len(packet) // vlen) tags.append(tag) offset = offset + len(packet) return data, tags diff --git a/gnuradio-runtime/python/gnuradio/gr/pubsub.py b/gnuradio-runtime/python/gnuradio/gr/pubsub.py index 90568418fc..25108b8f70 100644 --- a/gnuradio-runtime/python/gnuradio/gr/pubsub.py +++ b/gnuradio-runtime/python/gnuradio/gr/pubsub.py @@ -26,43 +26,46 @@ Abstract GNU Radio publisher/subscriber interface This is a proof of concept implementation, will likely change significantly. """ +from __future__ import print_function +from __future__ import unicode_literals + class pubsub(dict): def __init__(self): - self._publishers = { } - self._subscribers = { } - self._proxies = { } + self._publishers = { } + self._subscribers = { } + self._proxies = { } def __missing__(self, key, value=None): - dict.__setitem__(self, key, value) - self._publishers[key] = None - self._subscribers[key] = [] - self._proxies[key] = None + dict.__setitem__(self, key, value) + self._publishers[key] = None + self._subscribers[key] = [] + self._proxies[key] = None def __setitem__(self, key, val): - if not self.has_key(key): - self.__missing__(key, val) - elif self._proxies[key] is not None: - (p, newkey) = self._proxies[key] - p[newkey] = val - else: - dict.__setitem__(self, key, val) - for sub in self._subscribers[key]: - # Note this means subscribers will get called in the thread - # context of the 'set' caller. - sub(val) + if key not in self: + self.__missing__(key, val) + elif self._proxies[key] is not None: + (p, newkey) = self._proxies[key] + p[newkey] = val + else: + dict.__setitem__(self, key, val) + for sub in self._subscribers[key]: + # Note this means subscribers will get called in the thread + # context of the 'set' caller. + sub(val) def __getitem__(self, key): - if not self.has_key(key): self.__missing__(key) - if self._proxies[key] is not None: - (p, newkey) = self._proxies[key] - return p[newkey] - elif self._publishers[key] is not None: - return self._publishers[key]() - else: - return dict.__getitem__(self, key) + if key not in self: self.__missing__(key) + if self._proxies[key] is not None: + (p, newkey) = self._proxies[key] + return p[newkey] + elif self._publishers[key] is not None: + return self._publishers[key]() + else: + return dict.__getitem__(self, key) def publish(self, key, publisher): - if not self.has_key(key): self.__missing__(key) + if key not in self: self.__missing__(key) if self._proxies[key] is not None: (p, newkey) = self._proxies[key] p.publish(newkey, publisher) @@ -70,7 +73,7 @@ class pubsub(dict): self._publishers[key] = publisher def subscribe(self, key, subscriber): - if not self.has_key(key): self.__missing__(key) + if key not in self: self.__missing__(key) if self._proxies[key] is not None: (p, newkey) = self._proxies[key] p.subscribe(newkey, subscriber) @@ -92,9 +95,9 @@ class pubsub(dict): self._subscribers[key].remove(subscriber) def proxy(self, key, p, newkey=None): - if not self.has_key(key): self.__missing__(key) - if newkey is None: newkey = key - self._proxies[key] = (p, newkey) + if key not in self: self.__missing__(key) + if newkey is None: newkey = key + self._proxies[key] = (p, newkey) def unproxy(self, key): self._proxies[key] = None @@ -105,49 +108,49 @@ if __name__ == "__main__": o = pubsub() # Non-existent key gets auto-created with None value - print "Auto-created key 'foo' value:", o['foo'] + print("Auto-created key 'foo' value:", o['foo']) # Add some subscribers # First is a bare function def print_len(x): - print "len=%i" % (len(x), ) + print("len=%i" % (len(x), )) o.subscribe('foo', print_len) # The second is a class member function class subber(object): - def __init__(self, param): - self._param = param - def printer(self, x): - print self._param, `x` + def __init__(self, param): + self._param = param + def printer(self, x): + print(self._param, repr(x)) s = subber('param') o.subscribe('foo', s.printer) # The third is a lambda function - o.subscribe('foo', lambda x: sys.stdout.write('val='+`x`+'\n')) + o.subscribe('foo', lambda x: sys.stdout.write('val='+repr(x)+'\n')) # Update key 'foo', will notify subscribers - print "Updating 'foo' with three subscribers:" + print("Updating 'foo' with three subscribers:") o['foo'] = 'bar'; # Remove first subscriber o.unsubscribe('foo', print_len) # Update now will only trigger second and third subscriber - print "Updating 'foo' after removing a subscriber:" + print("Updating 'foo' after removing a subscriber:") o['foo'] = 'bar2'; # Publish a key as a function, in this case, a lambda function o.publish('baz', lambda : 42) - print "Published value of 'baz':", o['baz'] + print("Published value of 'baz':", o['baz']) # Unpublish the key o.unpublish('baz') # This will return None, as there is no publisher - print "Value of 'baz' with no publisher:", o['baz'] + print("Value of 'baz' with no publisher:", o['baz']) # Set 'baz' key, it gets cached o['baz'] = 'bazzz' # Now will return cached value, since no provider - print "Cached value of 'baz' after being set:", o['baz'] + print("Cached value of 'baz' after being set:", o['baz']) diff --git a/gnuradio-runtime/python/gnuradio/gr/qa_feval.py b/gnuradio-runtime/python/gnuradio/gr/qa_feval.py index 9018e12f36..078e2bf789 100755..100644 --- a/gnuradio-runtime/python/gnuradio/gr/qa_feval.py +++ b/gnuradio-runtime/python/gnuradio/gr/qa_feval.py @@ -20,6 +20,7 @@ # Boston, MA 02110-1301, USA. # + from gnuradio import gr, gr_unittest class my_add2_dd(gr.feval_dd): diff --git a/gnuradio-runtime/python/gnuradio/gr/qa_flowgraph.py b/gnuradio-runtime/python/gnuradio/gr/qa_flowgraph.py index fa4fd4910e..f5802c51bc 100755..100644 --- a/gnuradio-runtime/python/gnuradio/gr/qa_flowgraph.py +++ b/gnuradio-runtime/python/gnuradio/gr/qa_flowgraph.py @@ -20,6 +20,7 @@ # Boston, MA 02110-1301, USA. # + import time import pmt from gnuradio import gr, gr_unittest, blocks diff --git a/gnuradio-runtime/python/gnuradio/gr/qa_hier_block2.py b/gnuradio-runtime/python/gnuradio/gr/qa_hier_block2.py index 005331c2ec..c8f3d1a5f9 100644 --- a/gnuradio-runtime/python/gnuradio/gr/qa_hier_block2.py +++ b/gnuradio-runtime/python/gnuradio/gr/qa_hier_block2.py @@ -19,9 +19,12 @@ # Boston, MA 02110-1301, USA. # -import pmt, time +import time + from gnuradio import gr_unittest, blocks, gr, analog from gnuradio.gr.hier_block2 import _multiple_endpoints, _optional_endpoints +import pmt + class test_hblk(gr.hier_block2): def __init__(self, io_sig=1*[gr.sizeof_gr_complex], ndebug=2): @@ -126,7 +129,7 @@ class test_hier_block2(gr_unittest.TestCase): time.sleep(1) tb.stop() tb.wait() - + def test_012(self): s, st, h, k = analog.sig_source_c(44100, analog.GR_COS_WAVE, 440, 1.0, 0.0), blocks.message_strobe(pmt.PMT_NIL, 100), blocks.head(gr.sizeof_gr_complex, 1000), test_hblk([gr.sizeof_gr_complex], 16) tb = gr.top_block() @@ -139,4 +142,3 @@ class test_hier_block2(gr_unittest.TestCase): if __name__ == '__main__': gr_unittest.run(test_hier_block2, "test_hier_block2.xml") - diff --git a/gnuradio-runtime/python/gnuradio/gr/qa_kludged_imports.py b/gnuradio-runtime/python/gnuradio/gr/qa_kludged_imports.py index f80188c9fc..e2e9047c9b 100755..100644 --- a/gnuradio-runtime/python/gnuradio/gr/qa_kludged_imports.py +++ b/gnuradio-runtime/python/gnuradio/gr/qa_kludged_imports.py @@ -20,6 +20,7 @@ # Boston, MA 02110-1301, USA. # + from gnuradio import gr, gr_unittest class test_kludged_imports (gr_unittest.TestCase): diff --git a/gnuradio-runtime/python/gnuradio/gr/qa_random.py b/gnuradio-runtime/python/gnuradio/gr/qa_random.py index d3e5410454..6fbf5e478a 100644 --- a/gnuradio-runtime/python/gnuradio/gr/qa_random.py +++ b/gnuradio-runtime/python/gnuradio/gr/qa_random.py @@ -20,6 +20,7 @@ # Boston, MA 02110-1301, USA. # + from gnuradio import gr, gr_unittest import numpy as np diff --git a/gnuradio-runtime/python/gnuradio/gr/qa_tag_utils.py b/gnuradio-runtime/python/gnuradio/gr/qa_tag_utils.py index 55b62a12ac..3d7b99d12c 100755..100644 --- a/gnuradio-runtime/python/gnuradio/gr/qa_tag_utils.py +++ b/gnuradio-runtime/python/gnuradio/gr/qa_tag_utils.py @@ -20,12 +20,12 @@ # Boston, MA 02110-1301, USA. # +from __future__ import print_function + + from gnuradio import gr, gr_unittest +import pmt -try: - import pmt_swig as pmt -except ImportError: - import pmt class test_tag_utils (gr_unittest.TestCase): @@ -111,6 +111,6 @@ class test_tag_utils (gr_unittest.TestCase): if __name__ == '__main__': - print 'hi' + print('hi') gr_unittest.run(test_tag_utils, "test_tag_utils.xml") diff --git a/gnuradio-runtime/python/gnuradio/gr/tag_utils.py b/gnuradio-runtime/python/gnuradio/gr/tag_utils.py index 0d4805a8b8..d054865c22 100644 --- a/gnuradio-runtime/python/gnuradio/gr/tag_utils.py +++ b/gnuradio-runtime/python/gnuradio/gr/tag_utils.py @@ -1,6 +1,7 @@ +from __future__ import unicode_literals import pmt -import runtime_swig as gr +from . import runtime_swig as gr class PythonTag(object): " Python container for tags " @@ -51,29 +52,29 @@ def python_to_tag(tag_struct): good = False tag = gr.tag_t() if(type(tag_struct) == dict): - if(tag_struct.has_key('offset')): - if(isinstance(tag_struct['offset'], (int,long))): + if('offset' in tag_struct): + if(isinstance(tag_struct['offset'], int)): tag.offset = tag_struct['offset'] good = True - if(tag_struct.has_key('key')): + if('key' in tag_struct): if(isinstance(tag_struct['key'], pmt.swig_int_ptr)): tag.key = tag_struct['key'] good = True - if(tag_struct.has_key('value')): + if('value' in tag_struct): if(isinstance(tag_struct['value'], pmt.swig_int_ptr)): tag.value = tag_struct['value'] good = True - if(tag_struct.has_key('srcid')): + if('srcid' in tag_struct): if(isinstance(tag_struct['srcid'], pmt.swig_int_ptr)): tag.srcid = tag_struct['srcid'] good = True elif(type(tag_struct) == list or type(tag_struct) == tuple): if(len(tag_struct) == 4): - if(isinstance(tag_struct[0], (int,long))): + if(isinstance(tag_struct[0], int)): tag.offset = tag_struct[0] good = True @@ -90,7 +91,7 @@ def python_to_tag(tag_struct): good = True elif(len(tag_struct) == 3): - if(isinstance(tag_struct[0], (int,long))): + if(isinstance(tag_struct[0], int)): tag.offset = tag_struct[0] good = True diff --git a/gnuradio-runtime/python/gnuradio/gr/top_block.py b/gnuradio-runtime/python/gnuradio/gr/top_block.py index 2efcbd9aae..e7608bf5e9 100644 --- a/gnuradio-runtime/python/gnuradio/gr/top_block.py +++ b/gnuradio-runtime/python/gnuradio/gr/top_block.py @@ -19,15 +19,18 @@ # Boston, MA 02110-1301, USA. # -from runtime_swig import top_block_swig, \ - top_block_wait_unlocked, top_block_run_unlocked, \ - top_block_start_unlocked, top_block_stop_unlocked, \ - top_block_unlock_unlocked, dot_graph_tb +from __future__ import absolute_import +from __future__ import unicode_literals + +from .runtime_swig import (top_block_swig, + top_block_wait_unlocked, top_block_run_unlocked, + top_block_start_unlocked, top_block_stop_unlocked, + top_block_unlock_unlocked, dot_graph_tb) #import gnuradio.gr.gr_threading as _threading -import gr_threading as _threading +from . import gr_threading as _threading -from hier_block2 import hier_block2 +from .hier_block2 import hier_block2 class _top_block_waiter(_threading.Thread): """ diff --git a/gnuradio-runtime/python/gnuradio/gr_unittest.py b/gnuradio-runtime/python/gnuradio/gr_unittest.py index b20fa076de..1b8323ad7a 100755..100644 --- a/gnuradio-runtime/python/gnuradio/gr_unittest.py +++ b/gnuradio-runtime/python/gnuradio/gr_unittest.py @@ -22,10 +22,16 @@ """ GNU radio specific extension of unittest. """ +from __future__ import absolute_import +from __future__ import unicode_literals +from __future__ import division + +import os +import stat import unittest -import gr_xmlrunner -import sys, os, stat +from . import gr_xmlrunner + class TestCase(unittest.TestCase): """A subclass of unittest.TestCase that adds additional assertions @@ -43,11 +49,12 @@ class TestCase(unittest.TestCase): as significant digits (measured from the most significant digit). """ if round(second.real-first.real, places) != 0: - raise self.failureException, \ - (msg or '%s != %s within %s places' % (`first`, `second`, `places` )) + raise self.failureException( + msg or '%r != %r within %r places' % (first, second, places)) if round(second.imag-first.imag, places) != 0: - raise self.failureException, \ - (msg or '%s != %s within %s places' % (`first`, `second`, `places` )) + raise self.failureException( + msg or '%r != %r within %r places' % (first, second, places) + ) def assertComplexAlmostEqual2 (self, ref, x, abs_eps=1e-12, rel_eps=1e-6, msg=None): """ @@ -57,48 +64,52 @@ class TestCase(unittest.TestCase): return if abs(ref) > abs_eps: - if abs(ref-x)/abs(ref) > rel_eps: - raise self.failureException, \ - (msg or '%s != %s rel_error = %s rel_limit = %s' % ( - `ref`, `x`, abs(ref-x)/abs(ref), `rel_eps` )) + if abs(ref-x) / abs(ref) > rel_eps: + raise self.failureException( + msg or '%r != %r rel_error = %r rel_limit = %r' % ( + ref, x, abs(ref-x) / abs(ref), rel_eps + ) + ) else: - raise self.failureException, \ - (msg or '%s != %s rel_error = %s rel_limit = %s' % ( - `ref`, `x`, abs(ref-x)/abs(ref), `rel_eps` )) + raise self.failureException( + msg or '%r != %r rel_error = %r rel_limit = %r' % ( + ref, x, abs(ref-x) / abs(ref), rel_eps + ) + ) def assertComplexTuplesAlmostEqual (self, a, b, places=7, msg=None): self.assertEqual (len(a), len(b)) - for i in xrange (len(a)): + for i in range (len(a)): self.assertComplexAlmostEqual (a[i], b[i], places, msg) def assertComplexTuplesAlmostEqual2 (self, ref, x, abs_eps=1e-12, rel_eps=1e-6, msg=None): self.assertEqual (len(ref), len(x)) - for i in xrange (len(ref)): + for i in range (len(ref)): try: self.assertComplexAlmostEqual2 (ref[i], x[i], abs_eps, rel_eps, msg) - except self.failureException, e: + except self.failureException as e: #sys.stderr.write("index = %d " % (i,)) - #sys.stderr.write("%s\n" % (e,)) + #sys.stderr.write("%r\n" % (e,)) raise def assertFloatTuplesAlmostEqual (self, a, b, places=7, msg=None): self.assertEqual (len(a), len(b)) - for i in xrange (len(a)): + for i in range (len(a)): self.assertAlmostEqual (a[i], b[i], places, msg) def assertFloatTuplesAlmostEqual2 (self, ref, x, abs_eps=1e-12, rel_eps=1e-6, msg=None): self.assertEqual (len(ref), len(x)) - for i in xrange (len(ref)): + for i in range (len(ref)): try: self.assertComplexAlmostEqual2 (ref[i], x[i], abs_eps, rel_eps, msg) - except self.failureException, e: + except self.failureException as e: #sys.stderr.write("index = %d " % (i,)) - #sys.stderr.write("%s\n" % (e,)) + #sys.stderr.write("%r\n" % (e,)) raise @@ -124,7 +135,7 @@ def run(PUT, filename=None): path = basepath + "/python" if not os.path.exists(basepath): - os.makedirs(basepath, 0750) + os.makedirs(basepath, mode=0o750) xmlrunner = None # only proceed if .unittests is writable @@ -132,13 +143,13 @@ def run(PUT, filename=None): if(st & stat.S_IWUSR > 0): # Test if path exists; if not, build it if not os.path.exists(path): - os.makedirs(path, 0750) + os.makedirs(path, mode=0o750) # Just for safety: make sure we can write here, too st = os.stat(path)[stat.ST_MODE] if(st & stat.S_IWUSR > 0): # Create an XML runner to filename - fout = file(path+"/"+filename, "w") + fout = open(path+"/"+filename, "w") xmlrunner = gr_xmlrunner.XMLTestRunner(fout) txtrunner = TextTestRunner(verbosity=1) @@ -148,7 +159,7 @@ def run(PUT, filename=None): suite = TestLoader().loadTestsFromTestCase(PUT) # use the xmlrunner if we can write the the directory - if(xmlrunner is not None): + if xmlrunner is not None: xmlrunner.run(suite) main() diff --git a/gnuradio-runtime/python/gnuradio/gr_xmlrunner.py b/gnuradio-runtime/python/gnuradio/gr_xmlrunner.py index 31298197ff..fccb1b76f0 100644 --- a/gnuradio-runtime/python/gnuradio/gr_xmlrunner.py +++ b/gnuradio-runtime/python/gnuradio/gr_xmlrunner.py @@ -1,25 +1,56 @@ """ XML Test Runner for PyUnit """ - # Written by Sebastian Rittau <srittau@jroger.in-berlin.de> and placed in # the Public Domain. With contributions by Paolo Borelli and others. # Added to GNU Radio Oct. 3, 2010 -__version__ = "0.1" +from __future__ import unicode_literals import os.path import re import sys import time -import traceback import unittest +import linecache from xml.sax.saxutils import escape +from io import StringIO + + +__version__ = "0.1" -try: - from StringIO import StringIO -except ImportError: - from io import StringIO + +# inline trackeback.print_tb so that py2 uses unicode literals (py2/3 compat) +def print_tb(tb, limit=None, out=None): + """Print up to 'limit' stack trace entries from the traceback 'tb'. + + If 'limit' is omitted or None, all entries are printed. If 'file' + is omitted or None, the output goes to sys.stderr; otherwise + 'file' should be an open file or file-like object with a write() + method. + """ + def _print(out, s='', terminator='\n'): + out.write(s+terminator) + + if out is None: + out = sys.stderr + if limit is None: + if hasattr(sys, 'tracebacklimit'): + limit = sys.tracebacklimit + n = 0 + while tb is not None and (limit is None or n < limit): + f = tb.tb_frame + lineno = tb.tb_lineno + co = f.f_code + filename = co.co_filename + name = co.co_name + _print(out, ' Out "%s", line %d, in %s' % (filename, lineno, name)) + linecache.checkcache(filename) + line = linecache.getline(filename, lineno, f.f_globals) + if line: + _print(out, ' ' + line.strip()) + tb = tb.tb_next + n = n+1 class _TestInfo(object): @@ -60,12 +91,12 @@ class _TestInfo(object): supplied stream. """ - stream.write(' <testcase classname="%(class)s" name="%(method)s" time="%(time).4f">' % \ - { - "class": self._class, - "method": self._method, - "time": self._time, - }) + stream.write(' <testcase classname="%(class)s" name="%(method)s" time="%(time).4f">' % + { + 'class': self._class, + 'method': self._method, + 'time': self._time, + }) if self._failure is not None: self._print_error(stream, 'failure', self._failure) if self._error is not None: @@ -76,10 +107,10 @@ class _TestInfo(object): """Print information from a failure or error to the supplied stream.""" text = escape(str(error[1])) stream.write('\n') - stream.write(' <%s type="%s">%s\n' \ - % (tagname, _clsname(error[0]), text)) + stream.write(' <%s type="%s">%s\n' + % (tagname, _clsname(error[0]), text)) tb_stream = StringIO() - traceback.print_tb(error[2], None, tb_stream) + print_tb(error[2], None, tb_stream) stream.write(escape(tb_stream.getvalue())) stream.write(' </%s>\n' % tagname) stream.write(' ') @@ -137,14 +168,17 @@ class _XMLTestResult(unittest.TestResult): output and standard error streams must be passed in.a """ - stream.write('<testsuite errors="%(e)d" failures="%(f)d" ' % \ - { "e": len(self.errors), "f": len(self.failures) }) - stream.write('name="%(n)s" tests="%(t)d" time="%(time).3f">\n' % \ - { - "n": self._test_name, - "t": self.testsRun, - "time": time_taken, - }) + stream.write('<testsuite errors="%(e)d" failures="%(f)d" ' % + { + "e": len(self.errors), + "f": len(self.failures) + }) + stream.write('name="%(n)s" tests="%(t)d" time="%(time).3f">\n' % + { + "n": self._test_name, + "t": self.testsRun, + "time": time_taken + }) for info in self._tests: info.print_report(stream) stream.write(' <system-out><![CDATA[%s]]></system-out>\n' % out) @@ -173,9 +207,9 @@ class XMLTestRunner(object): """Run the given test case or test suite.""" class_ = test.__class__ classname = class_.__module__ + "." + class_.__name__ - if self._stream == None: + if self._stream is None: filename = "TEST-%s.xml" % classname - stream = file(os.path.join(self._path, filename), "w") + stream = open(os.path.join(self._path, filename), "w") stream.write('<?xml version="1.0" encoding="utf-8"?>\n') else: stream = self._stream diff --git a/gnuradio-runtime/python/gnuradio/gru/__init__.py b/gnuradio-runtime/python/gnuradio/gru/__init__.py index 4e41d03a74..0948edb17f 100644 --- a/gnuradio-runtime/python/gnuradio/gru/__init__.py +++ b/gnuradio-runtime/python/gnuradio/gru/__init__.py @@ -1,13 +1,15 @@ +from __future__ import absolute_import +from __future__ import unicode_literals # make this a package # Import gru stuff -from daemon import * -from freqz import * -from gnuplot_freqz import * -from hexint import * -from listmisc import * -from mathmisc import * -from msgq_runner import * -from os_read_exactly import * -from seq_with_cursor import * -from socket_stuff import * +from .daemon import * +from .freqz import * +from .gnuplot_freqz import * +from .hexint import * +from .listmisc import * +from .mathmisc import * +from .msgq_runner import * +from .os_read_exactly import * +from .seq_with_cursor import * +from .socket_stuff import * diff --git a/gnuradio-runtime/python/gnuradio/gru/daemon.py b/gnuradio-runtime/python/gnuradio/gru/daemon.py index e04702152d..14138f9730 100644 --- a/gnuradio-runtime/python/gnuradio/gru/daemon.py +++ b/gnuradio-runtime/python/gnuradio/gru/daemon.py @@ -18,6 +18,10 @@ # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # + +from __future__ import print_function +from __future__ import unicode_literals + import os, sys, signal # Turn application into a background daemon process. @@ -55,38 +59,38 @@ import os, sys, signal def daemonize(pidfile=None, logfile=None): # fork() into background try: - pid = os.fork() - except OSError, e: - raise Exception, "%s [%d]" % (e.strerror, e.errno) + pid = os.fork() + except OSError as e: + raise Exception("%s [%d]" % (e.strerror, e.errno)) if pid == 0: # First child of first fork() - # Become session leader of new session - os.setsid() + # Become session leader of new session + os.setsid() - # fork() into background again - try: - pid = os.fork() - except OSError, e: - raise Exception, "%s [%d]" % (e.strerror, e.errno) + # fork() into background again + try: + pid = os.fork() + except OSError as e: + raise Exception("%s [%d]" % (e.strerror, e.errno)) - if pid != 0: - os._exit(0) # Second child of second fork() + if pid != 0: + os._exit(0) # Second child of second fork() - else: # Second child of first fork() - os._exit(0) + else: # Second child of first fork() + os._exit(0) - os.umask(0111) + os.umask(0o111) # Write pid pid = os.getpid() if pidfile is not None: - open(pidfile, 'w').write('%d\n'%pid) + open(pidfile, 'w').write('%d\n'%pid) # Redirect streams if logfile is not None: - lf = open(logfile, 'a+') - sys.stdout = lf - sys.stderr = lf + lf = open(logfile, 'a+') + sys.stdout = lf + sys.stderr = lf # Prevent pinning any filesystem mounts os.chdir('/') @@ -97,6 +101,6 @@ def daemonize(pidfile=None, logfile=None): if __name__ == "__main__": import time daemonize() - print "Hello, world, from daemon process." + print("Hello, world, from daemon process.") time.sleep(20) - print "Goodbye, world, from daemon process." + print("Goodbye, world, from daemon process.") diff --git a/gnuradio-runtime/python/gnuradio/gru/freqz.py b/gnuradio-runtime/python/gnuradio/gru/freqz.py index a24d13ddee..edea6113b6 100644 --- a/gnuradio-runtime/python/gnuradio/gru/freqz.py +++ b/gnuradio-runtime/python/gnuradio/gru/freqz.py @@ -52,6 +52,8 @@ # DAMAGE. # +from __future__ import division +from __future__ import unicode_literals __all__ = ['freqz'] import numpy @@ -106,7 +108,7 @@ def polyval(p,x): y = x * y + p[i] return y -class poly1d: +class poly1d(object): """A one-dimensional polynomial class. p = poly1d([1,2,3]) constructs the polynomial x**2 + 2 x + 3 @@ -125,14 +127,14 @@ class poly1d: """ def __init__(self, c_or_r, r=0): if isinstance(c_or_r,poly1d): - for key in c_or_r.__dict__.keys(): + for key in list(c_or_r.__dict__.keys()): self.__dict__[key] = c_or_r.__dict__[key] return if r: c_or_r = poly(c_or_r) c_or_r = atleast_1d(c_or_r) if len(c_or_r.shape) > 1: - raise ValueError, "Polynomial must be 1d only." + raise ValueError("Polynomial must be 1d only.") c_or_r = trim_zeros(c_or_r, trim='f') if len(c_or_r) == 0: c_or_r = numpy.array([0]) @@ -227,7 +229,7 @@ class poly1d: def __pow__(self, val): if not isscalar(val) or int(val) != val or val < 0: - raise ValueError, "Power to non-negative integers only." + raise ValueError("Power to non-negative integers only.") res = [1] for k in range(val): res = polymul(self.coeffs, res) @@ -243,20 +245,20 @@ class poly1d: def __div__(self, other): if isscalar(other): - return poly1d(self.coeffs/other) + return poly1d(self.coeffs / other) else: other = poly1d(other) - return map(poly1d,polydiv(self.coeffs, other.coeffs)) + return list(map(poly1d,polydiv(self.coeffs, other.coeffs))) def __rdiv__(self, other): if isscalar(other): - return poly1d(other/self.coeffs) + return poly1d(other / self.coeffs) else: other = poly1d(other) - return map(poly1d,polydiv(other.coeffs, self.coeffs)) + return list(map(poly1d,polydiv(other.coeffs, self.coeffs))) def __setattr__(self, key, val): - raise ValueError, "Attributes cannot be changed this way." + raise ValueError("Attributes cannot be changed this way.") def __getattr__(self, key): if key in ['r','roots']: @@ -279,7 +281,7 @@ class poly1d: def __setitem__(self, key, val): ind = self.order - key if key < 0: - raise ValueError, "Does not support negative powers." + raise ValueError("Does not support negative powers.") if key > self.order: zr = numpy.zeros(key-self.order,self.coeffs.typecode()) self.__dict__['coeffs'] = numpy.concatenate((zr,self.coeffs)) @@ -323,22 +325,22 @@ def freqz(b, a, worN=None, whole=0, plot=None): h -- The frequency response. w -- The frequencies at which h was computed. """ - b, a = map(atleast_1d, (b,a)) + b, a = list(map(atleast_1d, (b,a))) if whole: lastpoint = 2*pi else: lastpoint = pi if worN is None: N = 512 - w = Num.arange(0,lastpoint,lastpoint/N) - elif isinstance(worN, types.IntType): + w = Num.arange(0,lastpoint,lastpoint / N) + elif isinstance(worN, int): N = worN - w = Num.arange(0,lastpoint,lastpoint/N) + w = Num.arange(0,lastpoint,lastpoint / N) else: w = worN w = atleast_1d(w) zm1 = exp(-1j*w) - h = polyval(b[::-1], zm1) / polyval(a[::-1], zm1) + h = polyval(b[::-1] / zm1, polyval(a[::-1], zm1)) # if not plot is None: # plot(w, h) return h, w diff --git a/gnuradio-runtime/python/gnuradio/gru/gnuplot_freqz.py b/gnuradio-runtime/python/gnuradio/gru/gnuplot_freqz.py index dd483e4277..71aee11f0b 100755..100644 --- a/gnuradio-runtime/python/gnuradio/gru/gnuplot_freqz.py +++ b/gnuradio-runtime/python/gnuradio/gru/gnuplot_freqz.py @@ -20,6 +20,8 @@ # Boston, MA 02110-1301, USA. # +from __future__ import division +from __future__ import unicode_literals __all__ = ['gnuplot_freqz'] import tempfile @@ -46,10 +48,10 @@ def gnuplot_freqz (hw, Fs=None, logfreq=False): h, w = hw ampl = 20 * numpy.log10 (numpy.absolute (h) + 1e-9) - phase = map (lambda x: math.atan2 (x.imag, x.real), h) + phase = [math.atan2 (x.imag, x.real) for x in h] if Fs: - w *= (Fs/(2*math.pi)) + w *= (Fs / (2*math.pi)) for freq, a, ph in zip (w, ampl, phase): data_file.write ("%g\t%g\t%g\n" % (freq, a, ph)) @@ -99,4 +101,4 @@ def test_plot (): if __name__ == '__main__': handle = test_plot () - raw_input ('Press Enter to continue: ') + input ('Press Enter to continue: ') diff --git a/gnuradio-runtime/python/gnuradio/gru/hexint.py b/gnuradio-runtime/python/gnuradio/gru/hexint.py index 0fb5ecde04..096b876701 100644 --- a/gnuradio-runtime/python/gnuradio/gru/hexint.py +++ b/gnuradio-runtime/python/gnuradio/gru/hexint.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals # # Copyright 2005 Free Software Foundation, Inc. # diff --git a/gnuradio-runtime/python/gnuradio/gru/listmisc.py b/gnuradio-runtime/python/gnuradio/gru/listmisc.py index 9e70eb863c..a981147337 100644 --- a/gnuradio-runtime/python/gnuradio/gru/listmisc.py +++ b/gnuradio-runtime/python/gnuradio/gru/listmisc.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals # # Copyright 2005 Free Software Foundation, Inc. # diff --git a/gnuradio-runtime/python/gnuradio/gru/mathmisc.py b/gnuradio-runtime/python/gnuradio/gru/mathmisc.py index 7e6f23a346..790d7c993c 100644 --- a/gnuradio-runtime/python/gnuradio/gru/mathmisc.py +++ b/gnuradio-runtime/python/gnuradio/gru/mathmisc.py @@ -1,3 +1,5 @@ +from __future__ import division +from __future__ import unicode_literals # # Copyright 2005 Free Software Foundation, Inc. # @@ -30,4 +32,4 @@ def lcm(a,b): return a * b / gcd(a, b) def log2(x): - return math.log(x)/math.log(2) + return math.log(x) / math.log(2) diff --git a/gnuradio-runtime/python/gnuradio/gru/msgq_runner.py b/gnuradio-runtime/python/gnuradio/gru/msgq_runner.py index 767a74a717..2d58480f5f 100644 --- a/gnuradio-runtime/python/gnuradio/gru/msgq_runner.py +++ b/gnuradio-runtime/python/gnuradio/gru/msgq_runner.py @@ -40,6 +40,7 @@ To manually stop the runner, call stop() on the object. To determine if the runner has exited, call exited() on the object. """ +from __future__ import unicode_literals from gnuradio import gr import gnuradio.gr.gr_threading as _threading @@ -66,7 +67,7 @@ class msgq_runner(_threading.Thread): else: try: self._callback(msg) - except Exception, e: + except Exception as e: if self._exit_on_error: self._exit_error = e self.stop() diff --git a/gnuradio-runtime/python/gnuradio/gru/os_read_exactly.py b/gnuradio-runtime/python/gnuradio/gru/os_read_exactly.py index 40b053770e..c079fc4e11 100644 --- a/gnuradio-runtime/python/gnuradio/gru/os_read_exactly.py +++ b/gnuradio-runtime/python/gnuradio/gru/os_read_exactly.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals # # Copyright 2005 Free Software Foundation, Inc. # diff --git a/gnuradio-runtime/python/gnuradio/gru/seq_with_cursor.py b/gnuradio-runtime/python/gnuradio/gru/seq_with_cursor.py index def3299b69..0aefbf83bb 100644 --- a/gnuradio-runtime/python/gnuradio/gru/seq_with_cursor.py +++ b/gnuradio-runtime/python/gnuradio/gru/seq_with_cursor.py @@ -21,8 +21,12 @@ # misc utilities +from __future__ import absolute_import +from __future__ import division +from __future__ import unicode_literals + import types -import exceptions + class seq_with_cursor (object): __slots__ = [ 'items', 'index' ] @@ -40,7 +44,7 @@ class seq_with_cursor (object): elif initial_index >= 0 and initial_index < len (self.items): self.index = initial_index else: - raise exceptions.ValueError + raise ValueError def set_index_by_value(self, v): """ @@ -51,9 +55,9 @@ class seq_with_cursor (object): cv = self.current() more = True while cv < v and more: - cv, more = self.next() # side effect! + cv, more = next(self) # side effect! - def next (self): + def __next__ (self): new_index = self.index + 1 if new_index < len (self.items): self.index = new_index @@ -74,4 +78,3 @@ class seq_with_cursor (object): def get_seq (self): return self.items[:] # copy of items - diff --git a/gnuradio-runtime/python/gnuradio/gru/socket_stuff.py b/gnuradio-runtime/python/gnuradio/gru/socket_stuff.py index b7c5ac2fe1..ce08ce1e10 100644 --- a/gnuradio-runtime/python/gnuradio/gru/socket_stuff.py +++ b/gnuradio-runtime/python/gnuradio/gru/socket_stuff.py @@ -1,3 +1,4 @@ +from __future__ import unicode_literals # # Copyright 2005 Free Software Foundation, Inc. # @@ -37,7 +38,7 @@ def tcp_connect_or_die(sock_addr): s = socket.socket (socket.AF_INET, socket.SOCK_STREAM) try: s.connect(sock_addr) - except socket.error, err: + except socket.error as err: sys.stderr.write('Failed to connect to %s: %s\n' % (sock_addr, os.strerror (err.args[0]),)) sys.exit(1) @@ -55,7 +56,7 @@ def udp_connect_or_die(sock_addr): s = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(sock_addr) - except socket.error, err: + except socket.error as err: sys.stderr.write('Failed to connect to %s: %s\n' % (sock_addr, os.strerror (err.args[0]),)) sys.exit(1) diff --git a/gnuradio-runtime/python/pmt/CMakeLists.txt b/gnuradio-runtime/python/pmt/CMakeLists.txt index 1ddfc2a46f..7afac956cb 100644 --- a/gnuradio-runtime/python/pmt/CMakeLists.txt +++ b/gnuradio-runtime/python/pmt/CMakeLists.txt @@ -41,6 +41,6 @@ foreach(py_qa_test_file ${py_qa_test_files}) ${CMAKE_BINARY_DIR}/gnuradio-runtime/swig ) set(GR_TEST_TARGET_DEPS gnuradio-runtime) - GR_ADD_TEST(${py_qa_test_name} ${QA_PYTHON_EXECUTABLE} ${PYTHON_DASH_B} ${py_qa_test_file}) + GR_ADD_TEST(${py_qa_test_name} ${QA_PYTHON_EXECUTABLE} -B ${py_qa_test_file}) endforeach(py_qa_test_file) endif(ENABLE_TESTING) diff --git a/gnuradio-runtime/python/pmt/__init__.py b/gnuradio-runtime/python/pmt/__init__.py index 399fae8701..89eb555823 100644 --- a/gnuradio-runtime/python/pmt/__init__.py +++ b/gnuradio-runtime/python/pmt/__init__.py @@ -39,14 +39,17 @@ bool, symbol (string), integer, real, complex, null, pair, list, vector, dict, uniform_vector, any (boost::any cast) ''' +from __future__ import absolute_import +from __future__ import unicode_literals + import os try: - from pmt_swig import * + from .pmt_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) - from pmt_swig import * + from .pmt_swig import * # due to changes in the PMT_NIL singleton for static builds, we force # this into Python here. @@ -55,5 +58,5 @@ PMT_T = get_PMT_T() PMT_F = get_PMT_F() PMT_EOF = get_PMT_EOF() -from pmt_to_python import pmt_to_python as to_python -from pmt_to_python import python_to_pmt as to_pmt +from .pmt_to_python import pmt_to_python as to_python +from .pmt_to_python import python_to_pmt as to_pmt diff --git a/gnuradio-runtime/python/pmt/pmt_to_python.py b/gnuradio-runtime/python/pmt/pmt_to_python.py index 2909c93c21..270a1dd9e9 100644 --- a/gnuradio-runtime/python/pmt/pmt_to_python.py +++ b/gnuradio-runtime/python/pmt/pmt_to_python.py @@ -17,8 +17,9 @@ # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. -try: import pmt_swig as pmt -except: import pmt +from __future__ import unicode_literals + +from . import pmt_swig as pmt import numpy # SWIG isn't taking in the #define PMT_NIL; @@ -34,7 +35,7 @@ def pmt_to_tuple(p): return tuple(elems) def pmt_from_tuple(p): - args = map(python_to_pmt, p) + args = list(map(python_to_pmt, p)) return pmt.make_tuple(*args) def pmt_to_vector(p): @@ -62,7 +63,7 @@ def pmt_to_dict(p): def pmt_from_dict(p): d = pmt.make_dict() - for k, v in p.iteritems(): + for k, v in list(p.items()): #dict is immutable -> therefore pmt_dict_add returns the new dict d = pmt.dict_add(d, python_to_pmt(k), python_to_pmt(v)) return d @@ -88,27 +89,27 @@ uvector_mappings = dict([ (numpy_mappings[key][3], (numpy_mappings[key][2], key) def numpy_to_uvector(numpy_array): try: mapping = numpy_mappings[numpy_array.dtype] - pc = map(mapping[1], numpy.ravel(numpy_array)) + pc = list(map(mapping[1], numpy.ravel(numpy_array))) return mapping[0](numpy_array.size, pc) except KeyError: raise ValueError("unsupported numpy array dtype for conversion to pmt %s"%(numpy_array.dtype)) def uvector_to_numpy(uvector): - match = None - for test_func in uvector_mappings.keys(): - if test_func(uvector): - match = uvector_mappings[test_func] - return numpy.array(match[0](uvector), dtype = match[1]) - else: - raise ValueError("unsupported uvector data type for conversion to numpy array %s"%(uvector)) + match = None + for test_func in list(uvector_mappings.keys()): + if test_func(uvector): + match = uvector_mappings[test_func] + return numpy.array(match[0](uvector), dtype = match[1]) + else: + raise ValueError("unsupported uvector data type for conversion to numpy array %s"%(uvector)) type_mappings = ( #python type, check pmt type, to python, from python (None, pmt.is_null, lambda x: None, lambda x: PMT_NIL), (bool, pmt.is_bool, pmt.to_bool, pmt.from_bool), (str, pmt.is_symbol, pmt.symbol_to_string, pmt.string_to_symbol), - (unicode, lambda x: False, None, lambda x: pmt.string_to_symbol(x.encode('utf-8'))), + (str, lambda x: False, None, lambda x: pmt.string_to_symbol(x.encode('utf-8'))), (int, pmt.is_integer, pmt.to_long, pmt.from_long), - (long, pmt.is_uint64, lambda x: long(pmt.to_uint64(x)), pmt.from_uint64), + (int, pmt.is_uint64, lambda x: int(pmt.to_uint64(x)), pmt.from_uint64), (float, pmt.is_real, pmt.to_double, pmt.from_double), (complex, pmt.is_complex, pmt.to_complex, pmt.from_complex), (tuple, pmt.is_tuple, pmt_to_tuple, pmt_from_tuple), diff --git a/gnuradio-runtime/python/pmt/qa_pmt.py b/gnuradio-runtime/python/pmt/qa_pmt.py index 32cff62f44..0d87676a30 100755..100644 --- a/gnuradio-runtime/python/pmt/qa_pmt.py +++ b/gnuradio-runtime/python/pmt/qa_pmt.py @@ -20,6 +20,8 @@ # Boston, MA 02110-1301, USA. # +from __future__ import print_function + import unittest import pmt @@ -30,7 +32,7 @@ class test_pmt(unittest.TestCase): b = pmt.from_double(123765) d1 = pmt.make_dict() d2 = pmt.dict_add(d1, a, b) - print d2 + print(d2) def test02(self): const = 123765 diff --git a/gnuradio-runtime/python/pmt/qa_pmt_to_python.py b/gnuradio-runtime/python/pmt/qa_pmt_to_python.py index e63ade1843..18a8e2bcf5 100755..100644 --- a/gnuradio-runtime/python/pmt/qa_pmt_to_python.py +++ b/gnuradio-runtime/python/pmt/qa_pmt_to_python.py @@ -20,16 +20,19 @@ # Boston, MA 02110-1301, USA. # +from __future__ import absolute_import + + import unittest import pmt -import pmt_to_python as pmt2py +from pmt import pmt_to_python as pmt2py class test_pmt_to_python(unittest.TestCase): def test_pmt_from_double(self): b = pmt.from_double(123765) self.assertEqual(pmt.to_python(b), 123765) - t = pmt.to_pmt(range(5)) + t = pmt.to_pmt(list(range(5))) def test_numpy_to_uvector_and_reverse(self): import numpy as np diff --git a/gnuradio-runtime/swig/CMakeLists.txt b/gnuradio-runtime/swig/CMakeLists.txt index aeb95dfb72..9135f311c6 100644 --- a/gnuradio-runtime/swig/CMakeLists.txt +++ b/gnuradio-runtime/swig/CMakeLists.txt @@ -104,6 +104,7 @@ install( msg_queue.i pmt_swig.i prefs.i + py3compat.i realtime.i sync_block.i sync_decimator.i diff --git a/gnuradio-runtime/swig/basic_block.i b/gnuradio-runtime/swig/basic_block.i index cf75479bb8..363e121bc6 100644 --- a/gnuradio-runtime/swig/basic_block.i +++ b/gnuradio-runtime/swig/basic_block.i @@ -31,6 +31,10 @@ namespace std { %template(x_vector_basic_block_sptr) vector<gr::basic_block_sptr>; }; +%begin %{ +#define SWIG_PYTHON_2_UNICODE +%} + namespace gr { class gr::basic_block @@ -60,6 +64,8 @@ namespace gr { } #ifdef SWIGPYTHON +%import py3compat.i + %pythoncode %{ basic_block_sptr.__repr__ = lambda self: "<basic_block %s (%d)>" % (self.name(), self.unique_id ()) %} diff --git a/gnuradio-runtime/swig/gnuradio.i b/gnuradio-runtime/swig/gnuradio.i index 7056d28ff5..6e8a3093f2 100644 --- a/gnuradio-runtime/swig/gnuradio.i +++ b/gnuradio-runtime/swig/gnuradio.i @@ -77,3 +77,14 @@ %} %include <gnuradio/high_res_timer.h> + +//////////////////////////////////////////////////////////////////////// +// Python 2/3 compatibilty + +%begin %{ +#define SWIG_PYTHON_2_UNICODE +%} + +#ifdef SWIGPYTHON +%import py3compat.i +#endif diff --git a/gnuradio-runtime/swig/pmt_swig.i b/gnuradio-runtime/swig/pmt_swig.i index 2063a5c972..c627b7d3e6 100644 --- a/gnuradio-runtime/swig/pmt_swig.i +++ b/gnuradio-runtime/swig/pmt_swig.i @@ -25,6 +25,10 @@ %include "std_string.i" %include "stdint.i" +%begin %{ +#define SWIG_PYTHON_2_UNICODE +%} + %{ #include <boost/intrusive_ptr.hpp> #include <boost/shared_ptr.hpp> @@ -58,6 +62,8 @@ %template(pmt_vector_cfloat) std::vector< std::complex<float> >; %template(pmt_vector_cdouble) std::vector< std::complex<double> >; +%import py3compat.i + //////////////////////////////////////////////////////////////////////// // Language independent exception handler //////////////////////////////////////////////////////////////////////// diff --git a/gnuradio-runtime/swig/py3compat.i b/gnuradio-runtime/swig/py3compat.i new file mode 100644 index 0000000000..6e726c294f --- /dev/null +++ b/gnuradio-runtime/swig/py3compat.i @@ -0,0 +1,7 @@ +%begin %{ +#define SWIG_PYTHON_2_UNICODE +%} + +%pythonbegin %{ +from __future__ import absolute_import +%} |