summaryrefslogtreecommitdiff
path: root/gr-utils/python
diff options
context:
space:
mode:
authorMarcus Müller <marcus@hostalia.de>2018-08-31 23:02:22 +0200
committerMarcus Müller <marcus@hostalia.de>2018-08-31 23:02:22 +0200
commit254fe5e89403d4de1fa6663d09efdf946996aff3 (patch)
tree62877d7ac7fdedf6c397c51e22ac6f97eba97ddf /gr-utils/python
parent896d1c9da31963ecf5b0d90942c2af51ca998a69 (diff)
parent5ad935c3a3dd46ce2860b13e2b774e4841784616 (diff)
Merge remote-tracking branch 'origin/next' into merge_next
Diffstat (limited to 'gr-utils/python')
-rw-r--r--gr-utils/python/modtool/CMakeLists.txt4
-rw-r--r--gr-utils/python/modtool/__init__.py32
-rw-r--r--gr-utils/python/modtool/cmakefile_editor.py7
-rw-r--r--gr-utils/python/modtool/code_generator.py74
-rw-r--r--gr-utils/python/modtool/gr-newmod/cmake/Modules/GrMiscUtils.cmake231
-rw-r--r--gr-utils/python/modtool/gr-newmod/cmake/Modules/GrPython.cmake15
-rw-r--r--gr-utils/python/modtool/gr-newmod/cmake/Modules/GrSwig.cmake7
-rw-r--r--gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/__init__.py3
-rw-r--r--gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/base.py18
-rw-r--r--gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/doxyindex.py8
-rw-r--r--gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/__init__.py1
-rw-r--r--gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/compound.py8
-rw-r--r--gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/compoundsuper.py40
-rw-r--r--gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/index.py6
-rw-r--r--gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/indexsuper.py21
-rw-r--r--gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/text.py5
-rw-r--r--gr-utils/python/modtool/gr-newmod/docs/doxygen/swig_doc.py3
-rw-r--r--gr-utils/python/modtool/gr-newmod/lib/CMakeLists.txt3
-rw-r--r--gr-utils/python/modtool/gr-newmod/python/__init__.py1
-rw-r--r--gr-utils/python/modtool/gr-newmod/python/build_utils.py228
-rw-r--r--gr-utils/python/modtool/gr-newmod/python/build_utils_codes.py51
-rw-r--r--gr-utils/python/modtool/grc_xml_generator.py3
-rw-r--r--gr-utils/python/modtool/modtool_add.py139
-rw-r--r--gr-utils/python/modtool/modtool_base.py111
-rw-r--r--gr-utils/python/modtool/modtool_disable.py48
-rw-r--r--gr-utils/python/modtool/modtool_help.py67
-rw-r--r--gr-utils/python/modtool/modtool_info.py57
-rw-r--r--gr-utils/python/modtool/modtool_makexml.py57
-rw-r--r--gr-utils/python/modtool/modtool_newmod.py44
-rw-r--r--gr-utils/python/modtool/modtool_rename.py76
-rw-r--r--gr-utils/python/modtool/modtool_rm.py52
-rw-r--r--gr-utils/python/modtool/parser_cc_block.py16
-rw-r--r--gr-utils/python/modtool/scm.py9
-rw-r--r--gr-utils/python/modtool/templates.py548
-rw-r--r--gr-utils/python/modtool/util_functions.py17
-rw-r--r--gr-utils/python/utils/CMakeLists.txt3
-rwxr-xr-xgr-utils/python/utils/gr_modtool34
-rwxr-xr-xgr-utils/python/utils/gr_plot_char39
-rwxr-xr-xgr-utils/python/utils/gr_plot_const49
-rw-r--r--gr-utils/python/utils/gr_plot_fft8
-rwxr-xr-xgr-utils/python/utils/gr_plot_fft_c11
-rwxr-xr-xgr-utils/python/utils/gr_plot_fft_f12
-rwxr-xr-xgr-utils/python/utils/gr_plot_float33
-rwxr-xr-xgr-utils/python/utils/gr_plot_int31
-rwxr-xr-xgr-utils/python/utils/gr_plot_iq46
-rw-r--r--gr-utils/python/utils/gr_plot_psd8
-rwxr-xr-xgr-utils/python/utils/gr_plot_psd_c13
-rwxr-xr-xgr-utils/python/utils/gr_plot_psd_f13
-rwxr-xr-xgr-utils/python/utils/gr_plot_qt26
-rwxr-xr-xgr-utils/python/utils/gr_plot_short33
-rw-r--r--gr-utils/python/utils/gr_read_file_metadata28
-rwxr-xr-xgr-utils/python/utils/grcc92
-rw-r--r--gr-utils/python/utils/plot_data.py23
-rw-r--r--[-rwxr-xr-x]gr-utils/python/utils/plot_fft_base.py68
-rw-r--r--[-rwxr-xr-x]gr-utils/python/utils/plot_psd_base.py83
-rw-r--r--gr-utils/python/utils/pyqt_filter.py1
-rw-r--r--gr-utils/python/utils/pyqt_plot.py1
57 files changed, 992 insertions, 1673 deletions
diff --git a/gr-utils/python/modtool/CMakeLists.txt b/gr-utils/python/modtool/CMakeLists.txt
index 9ee38d61e6..5fc5b0287f 100644
--- a/gr-utils/python/modtool/CMakeLists.txt
+++ b/gr-utils/python/modtool/CMakeLists.txt
@@ -27,7 +27,6 @@ GR_PYTHON_INSTALL(FILES
modtool_add.py
modtool_base.py
modtool_disable.py
- modtool_help.py
modtool_info.py
modtool_makexml.py
modtool_newmod.py
@@ -38,13 +37,11 @@ GR_PYTHON_INSTALL(FILES
templates.py
util_functions.py
DESTINATION ${GR_PYTHON_DIR}/gnuradio/modtool
- COMPONENT "utils"
)
set(GR_PKG_MODTOOL_DATA_DIR ${GR_PKG_DATA_DIR}/modtool)
install(DIRECTORY gr-newmod
DESTINATION ${GR_PKG_MODTOOL_DATA_DIR}
- COMPONENT "utils"
)
@@ -61,6 +58,5 @@ configure_file(
install(
FILES ${CMAKE_CURRENT_BINARY_DIR}/modtool.conf
DESTINATION ${GR_PREFSDIR}
- COMPONENT "utils"
)
diff --git a/gr-utils/python/modtool/__init__.py b/gr-utils/python/modtool/__init__.py
index 0319b91326..b6d719ac1d 100644
--- a/gr-utils/python/modtool/__init__.py
+++ b/gr-utils/python/modtool/__init__.py
@@ -1,5 +1,7 @@
+from __future__ import absolute_import
+from __future__ import unicode_literals
#
-# Copyright 2013 Free Software Foundation, Inc.
+# Copyright 2013-2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
@@ -19,19 +21,17 @@
# Boston, MA 02110-1301, USA.
#
-from cmakefile_editor import CMakeFileEditor
-from code_generator import GRMTemplate
-from grc_xml_generator import GRCXMLGenerator
-from modtool_base import ModTool, ModToolException, get_class_dict
-from modtool_add import ModToolAdd
-from modtool_disable import ModToolDisable
-from modtool_info import ModToolInfo
-from modtool_makexml import ModToolMakeXML
-from modtool_newmod import ModToolNewModule
-from modtool_rm import ModToolRemove
-from modtool_rename import ModToolRename
-from templates import Templates
+from .cmakefile_editor import CMakeFileEditor
+from .grc_xml_generator import GRCXMLGenerator
+from .modtool_base import ModTool, ModToolException, get_modtool_modules
+from .modtool_add import ModToolAdd
+from .modtool_disable import ModToolDisable
+from .modtool_info import ModToolInfo
+from .modtool_makexml import ModToolMakeXML
+from .modtool_newmod import ModToolNewModule
+from .modtool_rm import ModToolRemove
+from .modtool_rename import ModToolRename
+from .templates import Templates
# Leave this at the end
-from modtool_help import ModToolHelp
-from parser_cc_block import ParserCCBlock
-from util_functions import *
+from .parser_cc_block import ParserCCBlock
+from .util_functions import *
diff --git a/gr-utils/python/modtool/cmakefile_editor.py b/gr-utils/python/modtool/cmakefile_editor.py
index 4148ad1960..1b644287f9 100644
--- a/gr-utils/python/modtool/cmakefile_editor.py
+++ b/gr-utils/python/modtool/cmakefile_editor.py
@@ -20,6 +20,9 @@
#
""" Edit CMakeLists.txt files """
+from __future__ import print_function
+from __future__ import unicode_literals
+
import re
class CMakeFileEditor(object):
@@ -126,9 +129,9 @@ class CMakeFileEditor(object):
comment_out_re = r'\n' + self.indent + comment_out_re
(self.cfile, nsubs) = re.subn(r'(\b'+fname+r'\b)\s*', comment_out_re, self.cfile)
if nsubs == 0:
- print "Warning: A replacement failed when commenting out %s. Check the CMakeFile.txt manually." % fname
+ print("Warning: A replacement failed when commenting out %s. Check the CMakeFile.txt manually." % fname)
elif nsubs > 1:
- print "Warning: Replaced %s %d times (instead of once). Check the CMakeFile.txt manually." % (fname, nsubs)
+ print("Warning: Replaced %s %d times (instead of once). Check the CMakeFile.txt manually." % (fname, nsubs))
def comment_out_lines(self, pattern, comment_str='#'):
""" Comments out all lines that match with pattern """
diff --git a/gr-utils/python/modtool/code_generator.py b/gr-utils/python/modtool/code_generator.py
index 99f91761af..d95434f577 100644
--- a/gr-utils/python/modtool/code_generator.py
+++ b/gr-utils/python/modtool/code_generator.py
@@ -1,5 +1,5 @@
#
-# Copyright 2013 Free Software Foundation, Inc.
+# Copyright 2013-2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
@@ -19,40 +19,44 @@
# Boston, MA 02110-1301, USA.
#
""" A code generator (needed by ModToolAdd) """
+from __future__ import absolute_import
+from __future__ import unicode_literals
-from templates import Templates
-import Cheetah.Template
-from util_functions import str_to_fancyc_comment
-from util_functions import str_to_python_comment
-from util_functions import strip_default_values
-from util_functions import strip_arg_types
-from util_functions import strip_arg_types_grc
+from mako.template import Template
+from .templates import Templates
+from .util_functions import str_to_fancyc_comment
+from .util_functions import str_to_python_comment
+from .util_functions import strip_default_values
+from .util_functions import strip_arg_types
+from .util_functions import strip_arg_types_grc
-class GRMTemplate(Cheetah.Template.Template):
- """ An extended template class """
- def __init__(self, src, searchList):
- self.grtypelist = {
- 'sync': 'sync_block',
- 'sink': 'sync_block',
- 'source': 'sync_block',
- 'decimator': 'sync_decimator',
- 'interpolator': 'sync_interpolator',
- 'general': 'block',
- 'tagged_stream': 'tagged_stream_block',
- 'hier': 'hier_block2',
- 'noblock': ''}
- searchList['str_to_fancyc_comment'] = str_to_fancyc_comment
- searchList['str_to_python_comment'] = str_to_python_comment
- searchList['strip_default_values'] = strip_default_values
- searchList['strip_arg_types'] = strip_arg_types
- searchList['strip_arg_types_grc'] = strip_arg_types_grc
- Cheetah.Template.Template.__init__(self, src, searchList=searchList)
- self.grblocktype = self.grtypelist[searchList['blocktype']]
- if searchList['is_component']:
- self.include_dir_prefix = "gnuradio/" + searchList['modname']
- else:
- self.include_dir_prefix = searchList['modname']
+GRTYPELIST = {
+ 'sync': 'sync_block',
+ 'sink': 'sync_block',
+ 'source': 'sync_block',
+ 'decimator': 'sync_decimator',
+ 'interpolator': 'sync_interpolator',
+ 'general': 'block',
+ 'tagged_stream': 'tagged_stream_block',
+ 'hier': 'hier_block2',
+ 'noblock': ''
+}
+
+def render_template(tpl_id, **kwargs):
+ """ Return the parsed and rendered template given by tpl_id """
+ # Choose template
+ tpl = Template(Templates[tpl_id])
+ # Set up all variables
+ kwargs['str_to_fancyc_comment'] = str_to_fancyc_comment
+ kwargs['str_to_python_comment'] = str_to_python_comment
+ kwargs['strip_default_values'] = strip_default_values
+ kwargs['strip_arg_types'] = strip_arg_types
+ kwargs['strip_arg_types_grc'] = strip_arg_types_grc
+ kwargs['grblocktype'] = GRTYPELIST[kwargs['blocktype']]
+ if kwargs['is_component']:
+ kwargs['include_dir_prefix'] = "gnuradio/" + kwargs['modname']
+ else:
+ kwargs['include_dir_prefix'] = kwargs['modname']
+ # Render and return
+ return tpl.render(**kwargs)
-def get_template(tpl_id, **kwargs):
- """ Return the template given by tpl_id, parsed through Cheetah """
- return str(GRMTemplate(Templates[tpl_id], searchList=kwargs))
diff --git a/gr-utils/python/modtool/gr-newmod/cmake/Modules/GrMiscUtils.cmake b/gr-utils/python/modtool/gr-newmod/cmake/Modules/GrMiscUtils.cmake
index 18b0e82565..6b7bbc9d20 100644
--- a/gr-utils/python/modtool/gr-newmod/cmake/Modules/GrMiscUtils.cmake
+++ b/gr-utils/python/modtool/gr-newmod/cmake/Modules/GrMiscUtils.cmake
@@ -136,18 +136,14 @@ endfunction(GR_LIBTOOL)
# Also handle gnuradio custom naming conventions w/ extras mode.
########################################################################
function(GR_LIBRARY_FOO target)
- #parse the arguments for component names
- include(CMakeParseArgumentsCopy)
- CMAKE_PARSE_ARGUMENTS(GR_LIBRARY "" "RUNTIME_COMPONENT;DEVEL_COMPONENT" "" ${ARGN})
-
#set additional target properties
set_target_properties(${target} PROPERTIES SOVERSION ${LIBVER})
#install the generated files like so...
install(TARGETS ${target}
- LIBRARY DESTINATION ${GR_LIBRARY_DIR} COMPONENT ${GR_LIBRARY_RUNTIME_COMPONENT} # .so/.dylib file
- ARCHIVE DESTINATION ${GR_LIBRARY_DIR} COMPONENT ${GR_LIBRARY_DEVEL_COMPONENT} # .lib file
- RUNTIME DESTINATION ${GR_RUNTIME_DIR} COMPONENT ${GR_LIBRARY_RUNTIME_COMPONENT} # .dll file
+ LIBRARY DESTINATION ${GR_LIBRARY_DIR} # .so/.dylib file
+ ARCHIVE DESTINATION ${GR_LIBRARY_DIR} # .lib file
+ RUNTIME DESTINATION ${GR_RUNTIME_DIR} # .dll file
)
#extras mode enabled automatically on linux
@@ -179,7 +175,7 @@ function(GR_LIBRARY_FOO target)
FILES
${CMAKE_CURRENT_BINARY_DIR}/lib${target}.so
${CMAKE_CURRENT_BINARY_DIR}/lib${target}-${LIBVER}.so.0
- DESTINATION ${GR_LIBRARY_DIR} COMPONENT ${GR_LIBRARY_RUNTIME_COMPONENT}
+ DESTINATION ${GR_LIBRARY_DIR}
)
endif(LIBRARY_EXTRAS)
@@ -217,49 +213,6 @@ function(GR_GEN_TARGET_DEPS name var)
endfunction(GR_GEN_TARGET_DEPS)
########################################################################
-# Control use of gr_logger
-# Usage:
-# GR_LOGGING()
-#
-# Will set ENABLE_GR_LOG to 1 by default.
-# Can manually set with -DENABLE_GR_LOG=0|1
-########################################################################
-function(GR_LOGGING)
- find_package(Log4cpp)
-
- OPTION(ENABLE_GR_LOG "Use gr_logger" ON)
- if(ENABLE_GR_LOG)
- # If gr_logger is enabled, make it usable
- add_definitions( -DENABLE_GR_LOG )
-
- # also test LOG4CPP; if we have it, use this version of the logger
- # otherwise, default to the stdout/stderr model.
- if(LOG4CPP_FOUND)
- SET(HAVE_LOG4CPP True CACHE INTERNAL "" FORCE)
- add_definitions( -DHAVE_LOG4CPP )
- else(not LOG4CPP_FOUND)
- SET(HAVE_LOG4CPP False CACHE INTERNAL "" FORCE)
- SET(LOG4CPP_INCLUDE_DIRS "" CACHE INTERNAL "" FORCE)
- SET(LOG4CPP_LIBRARY_DIRS "" CACHE INTERNAL "" FORCE)
- SET(LOG4CPP_LIBRARIES "" CACHE INTERNAL "" FORCE)
- endif(LOG4CPP_FOUND)
-
- SET(ENABLE_GR_LOG ${ENABLE_GR_LOG} CACHE INTERNAL "" FORCE)
-
- else(ENABLE_GR_LOG)
- SET(HAVE_LOG4CPP False CACHE INTERNAL "" FORCE)
- SET(LOG4CPP_INCLUDE_DIRS "" CACHE INTERNAL "" FORCE)
- SET(LOG4CPP_LIBRARY_DIRS "" CACHE INTERNAL "" FORCE)
- SET(LOG4CPP_LIBRARIES "" CACHE INTERNAL "" FORCE)
- endif(ENABLE_GR_LOG)
-
- message(STATUS "ENABLE_GR_LOG set to ${ENABLE_GR_LOG}.")
- message(STATUS "HAVE_LOG4CPP set to ${HAVE_LOG4CPP}.")
- message(STATUS "LOG4CPP_LIBRARIES set to ${LOG4CPP_LIBRARIES}.")
-
-endfunction(GR_LOGGING)
-
-########################################################################
# Run GRCC to compile .grc files into .py files.
#
# Usage: GRCC(filename, directory)
@@ -351,179 +304,3 @@ set(CMAKE_REQUIRED_LIBRARIES -lpthread)
)
GR_ADD_COND_DEF(HAVE_SCHED_SETSCHEDULER)
endmacro(GR_CHECK_LINUX_SCHED_AVAIL)
-
-########################################################################
-# Macros to generate source and header files from template
-########################################################################
-macro(GR_EXPAND_X_H component root)
-
- include(GrPython)
-
- file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py
-"#!${PYTHON_EXECUTABLE}
-
-import sys, os, re
-sys.path.append('${GR_RUNTIME_PYTHONPATH}')
-sys.path.append('${CMAKE_SOURCE_DIR}/python')
-os.environ['srcdir'] = '${CMAKE_CURRENT_SOURCE_DIR}'
-os.chdir('${CMAKE_CURRENT_BINARY_DIR}')
-
-if __name__ == '__main__':
- import build_utils
- root, inp = sys.argv[1:3]
- for sig in sys.argv[3:]:
- name = re.sub ('X+', sig, root)
- d = build_utils.standard_dict2(name, sig, '${component}')
- build_utils.expand_template(d, inp)
-")
-
- #make a list of all the generated headers
- unset(expanded_files_h)
- foreach(sig ${ARGN})
- string(REGEX REPLACE "X+" ${sig} name ${root})
- list(APPEND expanded_files_h ${CMAKE_CURRENT_BINARY_DIR}/${name}.h)
- endforeach(sig)
- unset(name)
-
- #create a command to generate the headers
- add_custom_command(
- OUTPUT ${expanded_files_h}
- DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.h.t
- COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B}
- ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py
- ${root} ${root}.h.t ${ARGN}
- )
-
- #install rules for the generated headers
- list(APPEND generated_includes ${expanded_files_h})
-
-endmacro(GR_EXPAND_X_H)
-
-macro(GR_EXPAND_X_CC_H component root)
-
- include(GrPython)
-
- file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py
-"#!${PYTHON_EXECUTABLE}
-
-import sys, os, re
-sys.path.append('${GR_RUNTIME_PYTHONPATH}')
-sys.path.append('${CMAKE_SOURCE_DIR}/python')
-os.environ['srcdir'] = '${CMAKE_CURRENT_SOURCE_DIR}'
-os.chdir('${CMAKE_CURRENT_BINARY_DIR}')
-
-if __name__ == '__main__':
- import build_utils
- root, inp = sys.argv[1:3]
- for sig in sys.argv[3:]:
- name = re.sub ('X+', sig, root)
- d = build_utils.standard_impl_dict2(name, sig, '${component}')
- build_utils.expand_template(d, inp)
-")
-
- #make a list of all the generated files
- unset(expanded_files_cc)
- unset(expanded_files_h)
- foreach(sig ${ARGN})
- string(REGEX REPLACE "X+" ${sig} name ${root})
- list(APPEND expanded_files_cc ${CMAKE_CURRENT_BINARY_DIR}/${name}.cc)
- list(APPEND expanded_files_h ${CMAKE_CURRENT_BINARY_DIR}/${name}.h)
- endforeach(sig)
- unset(name)
-
- #create a command to generate the source files
- add_custom_command(
- OUTPUT ${expanded_files_cc}
- DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.cc.t
- COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B}
- ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py
- ${root} ${root}.cc.t ${ARGN}
- )
-
- #create a command to generate the header files
- add_custom_command(
- OUTPUT ${expanded_files_h}
- DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}.h.t
- COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B}
- ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py
- ${root} ${root}.h.t ${ARGN}
- )
-
- #make source files depends on headers to force generation
- set_source_files_properties(${expanded_files_cc}
- PROPERTIES OBJECT_DEPENDS "${expanded_files_h}"
- )
-
- #install rules for the generated files
- list(APPEND generated_sources ${expanded_files_cc})
- list(APPEND generated_headers ${expanded_files_h})
-
-endmacro(GR_EXPAND_X_CC_H)
-
-macro(GR_EXPAND_X_CC_H_IMPL component root)
-
- include(GrPython)
-
- file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py
-"#!${PYTHON_EXECUTABLE}
-
-import sys, os, re
-sys.path.append('${GR_RUNTIME_PYTHONPATH}')
-sys.path.append('${CMAKE_SOURCE_DIR}/python')
-os.environ['srcdir'] = '${CMAKE_CURRENT_SOURCE_DIR}'
-os.chdir('${CMAKE_CURRENT_BINARY_DIR}')
-
-if __name__ == '__main__':
- import build_utils
- root, inp = sys.argv[1:3]
- for sig in sys.argv[3:]:
- name = re.sub ('X+', sig, root)
- d = build_utils.standard_dict(name, sig, '${component}')
- build_utils.expand_template(d, inp, '_impl')
-")
-
- #make a list of all the generated files
- unset(expanded_files_cc_impl)
- unset(expanded_files_h_impl)
- unset(expanded_files_h)
- foreach(sig ${ARGN})
- string(REGEX REPLACE "X+" ${sig} name ${root})
- list(APPEND expanded_files_cc_impl ${CMAKE_CURRENT_BINARY_DIR}/${name}_impl.cc)
- list(APPEND expanded_files_h_impl ${CMAKE_CURRENT_BINARY_DIR}/${name}_impl.h)
- list(APPEND expanded_files_h ${CMAKE_CURRENT_BINARY_DIR}/../include/gnuradio/${component}/${name}.h)
- endforeach(sig)
- unset(name)
-
- #create a command to generate the _impl.cc files
- add_custom_command(
- OUTPUT ${expanded_files_cc_impl}
- DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}_impl.cc.t
- COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B}
- ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py
- ${root} ${root}_impl.cc.t ${ARGN}
- )
-
- #create a command to generate the _impl.h files
- add_custom_command(
- OUTPUT ${expanded_files_h_impl}
- DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${root}_impl.h.t
- COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B}
- ${CMAKE_CURRENT_BINARY_DIR}/generate_helper.py
- ${root} ${root}_impl.h.t ${ARGN}
- )
-
- #make _impl.cc source files depend on _impl.h to force generation
- set_source_files_properties(${expanded_files_cc_impl}
- PROPERTIES OBJECT_DEPENDS "${expanded_files_h_impl}"
- )
-
- #make _impl.h source files depend on headers to force generation
- set_source_files_properties(${expanded_files_h_impl}
- PROPERTIES OBJECT_DEPENDS "${expanded_files_h}"
- )
-
- #install rules for the generated files
- list(APPEND generated_sources ${expanded_files_cc_impl})
- list(APPEND generated_headers ${expanded_files_h_impl})
-
-endmacro(GR_EXPAND_X_CC_H_IMPL)
diff --git a/gr-utils/python/modtool/gr-newmod/cmake/Modules/GrPython.cmake b/gr-utils/python/modtool/gr-newmod/cmake/Modules/GrPython.cmake
index c7b4027971..588236e8b8 100644
--- a/gr-utils/python/modtool/gr-newmod/cmake/Modules/GrPython.cmake
+++ b/gr-utils/python/modtool/gr-newmod/cmake/Modules/GrPython.cmake
@@ -37,11 +37,12 @@ if(PYTHON_EXECUTABLE)
else(PYTHON_EXECUTABLE)
#use the built-in find script
+ set(Python_ADDITIONAL_VERSIONS 3.4 3.5 3.6)
find_package(PythonInterp 2)
#and if that fails use the find program routine
if(NOT PYTHONINTERP_FOUND)
- find_program(PYTHON_EXECUTABLE NAMES python python2 python2.7 python2.6 python2.5)
+ find_program(PYTHON_EXECUTABLE NAMES python python2 python2.7)
if(PYTHON_EXECUTABLE)
set(PYTHONINTERP_FOUND TRUE)
endif(PYTHON_EXECUTABLE)
@@ -87,7 +88,7 @@ macro(GR_PYTHON_CHECK_MODULE desc mod cmd have)
try:
import ${mod}
assert ${cmd}
-except ImportError, AssertionError: exit(-1)
+except (ImportError, AssertionError): exit(-1)
except: pass
#########################################"
RESULT_VARIABLE ${have}
@@ -107,7 +108,7 @@ endmacro(GR_PYTHON_CHECK_MODULE)
if(NOT DEFINED GR_PYTHON_DIR)
execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "
from distutils import sysconfig
-print sysconfig.get_python_lib(plat_specific=True, prefix='')
+print(sysconfig.get_python_lib(plat_specific=True, prefix=''))
" OUTPUT_VARIABLE GR_PYTHON_DIR OUTPUT_STRIP_TRAILING_WHITESPACE
)
endif()
@@ -120,7 +121,7 @@ file(TO_CMAKE_PATH ${GR_PYTHON_DIR} GR_PYTHON_DIR)
function(GR_UNIQUE_TARGET desc)
file(RELATIVE_PATH reldir ${CMAKE_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR})
execute_process(COMMAND ${PYTHON_EXECUTABLE} -c "import re, hashlib
-unique = hashlib.md5('${reldir}${ARGN}').hexdigest()[:5]
+unique = hashlib.md5(b'${reldir}${ARGN}').hexdigest()[:5]
print(re.sub('\\W', '_', '${desc} ${reldir} ' + unique))"
OUTPUT_VARIABLE _target OUTPUT_STRIP_TRAILING_WHITESPACE)
add_custom_target(${_target} ALL DEPENDS ${ARGN})
@@ -131,7 +132,7 @@ endfunction(GR_UNIQUE_TARGET)
########################################################################
function(GR_PYTHON_INSTALL)
include(CMakeParseArgumentsCopy)
- CMAKE_PARSE_ARGUMENTS(GR_PYTHON_INSTALL "" "DESTINATION;COMPONENT" "FILES;PROGRAMS" ${ARGN})
+ CMAKE_PARSE_ARGUMENTS(GR_PYTHON_INSTALL "" "DESTINATION" "FILES;PROGRAMS" ${ARGN})
####################################################################
if(GR_PYTHON_INSTALL_FILES)
@@ -183,7 +184,6 @@ function(GR_PYTHON_INSTALL)
set(python_install_gen_targets ${pycfiles} ${pyofiles})
install(FILES ${python_install_gen_targets}
DESTINATION ${GR_PYTHON_INSTALL_DESTINATION}
- COMPONENT ${GR_PYTHON_INSTALL_COMPONENT}
)
####################################################################
@@ -220,7 +220,6 @@ function(GR_PYTHON_INSTALL)
install(PROGRAMS ${pyexefile} RENAME ${pyfile_name}
DESTINATION ${GR_PYTHON_INSTALL_DESTINATION}
- COMPONENT ${GR_PYTHON_INSTALL_COMPONENT}
)
endforeach(pyfile)
@@ -236,7 +235,7 @@ endfunction(GR_PYTHON_INSTALL)
file(WRITE ${CMAKE_BINARY_DIR}/python_compile_helper.py "
import sys, py_compile
files = sys.argv[1:]
-srcs, gens = files[:len(files)/2], files[len(files)/2:]
+srcs, gens = files[:len(files)//2], files[len(files)//2:]
for src, gen in zip(srcs, gens):
py_compile.compile(file=src, cfile=gen, doraise=True)
")
diff --git a/gr-utils/python/modtool/gr-newmod/cmake/Modules/GrSwig.cmake b/gr-utils/python/modtool/gr-newmod/cmake/Modules/GrSwig.cmake
index a1309aa61f..e23c770228 100644
--- a/gr-utils/python/modtool/gr-newmod/cmake/Modules/GrSwig.cmake
+++ b/gr-utils/python/modtool/gr-newmod/cmake/Modules/GrSwig.cmake
@@ -77,7 +77,7 @@ function(GR_SWIG_MAKE_DOCS output_file)
add_custom_command(
OUTPUT ${output_file}
DEPENDS ${input_files} ${stamp-file} ${OUTPUT_DIRECTORY}/xml/index.xml
- COMMAND ${PYTHON_EXECUTABLE} ${PYTHON_DASH_B}
+ COMMAND ${PYTHON_EXECUTABLE} -B
${CMAKE_SOURCE_DIR}/docs/doxygen/swig_doc.py
${OUTPUT_DIRECTORY}/xml
${output_file}
@@ -189,24 +189,21 @@ endmacro(GR_SWIG_MAKE)
# GR_SWIG_INSTALL(
# TARGETS target target target...
# [DESTINATION destination]
-# [COMPONENT component]
# )
########################################################################
macro(GR_SWIG_INSTALL)
include(CMakeParseArgumentsCopy)
- CMAKE_PARSE_ARGUMENTS(GR_SWIG_INSTALL "" "DESTINATION;COMPONENT" "TARGETS" ${ARGN})
+ CMAKE_PARSE_ARGUMENTS(GR_SWIG_INSTALL "" "DESTINATION" "TARGETS" ${ARGN})
foreach(name ${GR_SWIG_INSTALL_TARGETS})
install(TARGETS ${SWIG_MODULE_${name}_REAL_NAME}
DESTINATION ${GR_SWIG_INSTALL_DESTINATION}
- COMPONENT ${GR_SWIG_INSTALL_COMPONENT}
)
include(GrPython)
GR_PYTHON_INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${name}.py
DESTINATION ${GR_SWIG_INSTALL_DESTINATION}
- COMPONENT ${GR_SWIG_INSTALL_COMPONENT}
)
GR_LIBTOOL(
diff --git a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/__init__.py b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/__init__.py
index b4b10a1765..22f4eb351d 100644
--- a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/__init__.py
+++ b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/__init__.py
@@ -64,8 +64,9 @@ This line is uninformative and is only to test line breaks in the comments.
u'Outputs the vital aadvark statistics.'
"""
+from __future__ import unicode_literals
-from doxyindex import DoxyIndex, DoxyFunction, DoxyParam, DoxyClass, DoxyFile, DoxyNamespace, DoxyGroup, DoxyFriend, DoxyOther
+from .doxyindex import DoxyIndex, DoxyFunction, DoxyParam, DoxyClass, DoxyFile, DoxyNamespace, DoxyGroup, DoxyFriend, DoxyOther
def _test():
import os
diff --git a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/base.py b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/base.py
index 295eae4965..b21369221c 100644
--- a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/base.py
+++ b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/base.py
@@ -25,24 +25,26 @@ A base class is created.
Classes based upon this are used to make more user-friendly interfaces
to the doxygen xml docs than the generated classes provide.
"""
+from __future__ import print_function
+from __future__ import unicode_literals
import os
import pdb
from xml.parsers.expat import ExpatError
-from generated import compound
+from .generated import compound
class Base(object):
- class Duplicate(StandardError):
+ class Duplicate(Exception):
pass
- class NoSuchMember(StandardError):
+ class NoSuchMember(Exception):
pass
- class ParsingError(StandardError):
+ class ParsingError(Exception):
pass
def __init__(self, parse_data, top=None):
@@ -95,7 +97,7 @@ class Base(object):
for cls in self.mem_classes:
if cls.can_parse(mem):
return cls
- raise StandardError(("Did not find a class for object '%s'." \
+ raise Exception(("Did not find a class for object '%s'." \
% (mem.get_name())))
def convert_mem(self, mem):
@@ -103,11 +105,11 @@ class Base(object):
cls = self.get_cls(mem)
converted = cls.from_parse_data(mem, self.top)
if converted is None:
- raise StandardError('No class matched this object.')
+ raise Exception('No class matched this object.')
self.add_ref(converted)
return converted
- except StandardError, e:
- print e
+ except Exception as e:
+ print(e)
@classmethod
def includes(cls, inst):
diff --git a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/doxyindex.py b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/doxyindex.py
index db73852865..5401bf2666 100644
--- a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/doxyindex.py
+++ b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/doxyindex.py
@@ -23,12 +23,14 @@
Classes providing more user-friendly interfaces to the doxygen xml
docs than the generated classes provide.
"""
+from __future__ import absolute_import
+from __future__ import unicode_literals
import os
-from generated import index
-from base import Base
-from text import description
+from .generated import index
+from .base import Base
+from .text import description
class DoxyIndex(Base):
"""
diff --git a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/__init__.py b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/__init__.py
index 39823979f6..23095c1f34 100644
--- a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/__init__.py
+++ b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/__init__.py
@@ -5,3 +5,4 @@ These do the real work of parsing the doxygen xml files but the
resultant classes are not very friendly to navigate so the rest of the
doxyxml module processes them further.
"""
+from __future__ import unicode_literals
diff --git a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/compound.py b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/compound.py
index 1522ac23f1..acfa0dd5c6 100644
--- a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/compound.py
+++ b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/compound.py
@@ -3,15 +3,17 @@
"""
Generated Mon Feb 9 19:08:05 2009 by generateDS.py.
"""
+from __future__ import absolute_import
+from __future__ import unicode_literals
+
-from string import lower as str_lower
from xml.dom import minidom
from xml.dom import Node
import sys
-import compoundsuper as supermod
-from compoundsuper import MixedContainer
+from . import compoundsuper as supermod
+from .compoundsuper import MixedContainer
class DoxygenTypeSub(supermod.DoxygenType):
diff --git a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/compoundsuper.py b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/compoundsuper.py
index 6255dda163..6e984e13ec 100644
--- a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/compoundsuper.py
+++ b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/compoundsuper.py
@@ -4,12 +4,17 @@
# Generated Thu Jun 11 18:44:25 2009 by generateDS.py.
#
+from __future__ import print_function
+from __future__ import unicode_literals
+
import sys
-import getopt
-from string import lower as str_lower
+
from xml.dom import minidom
from xml.dom import Node
+import six
+
+
#
# User methods
#
@@ -19,9 +24,9 @@ from xml.dom import Node
try:
from generatedssuper import GeneratedsSuper
-except ImportError, exp:
+except ImportError as exp:
- class GeneratedsSuper:
+ class GeneratedsSuper(object):
def format_string(self, input_data, input_name=''):
return input_data
def format_integer(self, input_data, input_name=''):
@@ -64,7 +69,7 @@ def showIndent(outfile, level):
outfile.write(' ')
def quote_xml(inStr):
- s1 = (isinstance(inStr, basestring) and inStr or
+ s1 = (isinstance(inStr, six.string_types) and inStr or
'%s' % inStr)
s1 = s1.replace('&', '&amp;')
s1 = s1.replace('<', '&lt;')
@@ -72,7 +77,7 @@ def quote_xml(inStr):
return s1
def quote_attrib(inStr):
- s1 = (isinstance(inStr, basestring) and inStr or
+ s1 = (isinstance(inStr, six.string_types) and inStr or
'%s' % inStr)
s1 = s1.replace('&', '&amp;')
s1 = s1.replace('<', '&lt;')
@@ -102,7 +107,7 @@ def quote_python(inStr):
return '"""%s"""' % s1
-class MixedContainer:
+class MixedContainer(object):
# Constants for category:
CategoryNone = 0
CategoryText = 1
@@ -4221,7 +4226,7 @@ class codelineType(GeneratedsSuper):
if attrs.get('lineno'):
try:
self.lineno = int(attrs.get('lineno').value)
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad integer attribute (lineno): %s' % exp)
if attrs.get('refkind'):
self.refkind = attrs.get('refkind').value
@@ -4504,12 +4509,12 @@ class referenceType(GeneratedsSuper):
if attrs.get('endline'):
try:
self.endline = int(attrs.get('endline').value)
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad integer attribute (endline): %s' % exp)
if attrs.get('startline'):
try:
self.startline = int(attrs.get('startline').value)
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad integer attribute (startline): %s' % exp)
if attrs.get('refid'):
self.refid = attrs.get('refid').value
@@ -4627,17 +4632,17 @@ class locationType(GeneratedsSuper):
if attrs.get('bodystart'):
try:
self.bodystart = int(attrs.get('bodystart').value)
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad integer attribute (bodystart): %s' % exp)
if attrs.get('line'):
try:
self.line = int(attrs.get('line').value)
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad integer attribute (line): %s' % exp)
if attrs.get('bodyend'):
try:
self.bodyend = int(attrs.get('bodyend').value)
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad integer attribute (bodyend): %s' % exp)
if attrs.get('bodyfile'):
self.bodyfile = attrs.get('bodyfile').value
@@ -6778,12 +6783,12 @@ class docTableType(GeneratedsSuper):
if attrs.get('rows'):
try:
self.rows = int(attrs.get('rows').value)
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad integer attribute (rows): %s' % exp)
if attrs.get('cols'):
try:
self.cols = int(attrs.get('cols').value)
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad integer attribute (cols): %s' % exp)
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.ELEMENT_NODE and \
@@ -7108,7 +7113,7 @@ class docHeadingType(GeneratedsSuper):
if attrs.get('level'):
try:
self.level = int(attrs.get('level').value)
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad integer attribute (level): %s' % exp)
def buildChildren(self, child_, nodeName_):
if child_.nodeType == Node.TEXT_NODE:
@@ -8283,7 +8288,7 @@ Options:
"""
def usage():
- print USAGE_TEXT
+ print(USAGE_TEXT)
sys.exit(1)
@@ -8339,4 +8344,3 @@ if __name__ == '__main__':
main()
#import pdb
#pdb.run('main()')
-
diff --git a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/index.py b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/index.py
index 7a70e14a1a..0c63512119 100644
--- a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/index.py
+++ b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/index.py
@@ -3,14 +3,16 @@
"""
Generated Mon Feb 9 19:08:05 2009 by generateDS.py.
"""
+from __future__ import absolute_import
+from __future__ import unicode_literals
from xml.dom import minidom
import os
import sys
-import compound
+from . import compound
-import indexsuper as supermod
+from . import indexsuper as supermod
class DoxygenTypeSub(supermod.DoxygenType):
def __init__(self, version=None, compound=None):
diff --git a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/indexsuper.py b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/indexsuper.py
index a991530198..11312db635 100644
--- a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/indexsuper.py
+++ b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/generated/indexsuper.py
@@ -4,12 +4,16 @@
# Generated Thu Jun 11 18:43:54 2009 by generateDS.py.
#
+from __future__ import print_function
+from __future__ import unicode_literals
+
import sys
-import getopt
-from string import lower as str_lower
+
from xml.dom import minidom
from xml.dom import Node
+import six
+
#
# User methods
#
@@ -19,9 +23,9 @@ from xml.dom import Node
try:
from generatedssuper import GeneratedsSuper
-except ImportError, exp:
+except ImportError as exp:
- class GeneratedsSuper:
+ class GeneratedsSuper(object):
def format_string(self, input_data, input_name=''):
return input_data
def format_integer(self, input_data, input_name=''):
@@ -64,7 +68,7 @@ def showIndent(outfile, level):
outfile.write(' ')
def quote_xml(inStr):
- s1 = (isinstance(inStr, basestring) and inStr or
+ s1 = (isinstance(inStr, six.string_types) and inStr or
'%s' % inStr)
s1 = s1.replace('&', '&amp;')
s1 = s1.replace('<', '&lt;')
@@ -72,7 +76,7 @@ def quote_xml(inStr):
return s1
def quote_attrib(inStr):
- s1 = (isinstance(inStr, basestring) and inStr or
+ s1 = (isinstance(inStr, six.string_types) and inStr or
'%s' % inStr)
s1 = s1.replace('&', '&amp;')
s1 = s1.replace('<', '&lt;')
@@ -102,7 +106,7 @@ def quote_python(inStr):
return '"""%s"""' % s1
-class MixedContainer:
+class MixedContainer(object):
# Constants for category:
CategoryNone = 0
CategoryText = 1
@@ -462,7 +466,7 @@ Options:
"""
def usage():
- print USAGE_TEXT
+ print(USAGE_TEXT)
sys.exit(1)
@@ -520,4 +524,3 @@ if __name__ == '__main__':
main()
#import pdb
#pdb.run('main()')
-
diff --git a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/text.py b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/text.py
index ce0999f191..caf0b05480 100644
--- a/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/text.py
+++ b/gr-utils/python/modtool/gr-newmod/docs/doxygen/doxyxml/text.py
@@ -22,12 +22,13 @@
"""
Utilities for extracting text from generated classes.
"""
+from __future__ import unicode_literals
def is_string(txt):
if isinstance(txt, str):
return True
try:
- if isinstance(txt, unicode):
+ if isinstance(txt, str):
return True
except NameError:
pass
@@ -50,7 +51,7 @@ def description_bit(obj):
elif is_string(obj):
return obj
else:
- raise StandardError('Expecting a string or something with content, content_ or value attribute')
+ raise Exception('Expecting a string or something with content, content_ or value attribute')
# If this bit is a paragraph then add one some line breaks.
if hasattr(obj, 'name') and obj.name == 'para':
result += "\n\n"
diff --git a/gr-utils/python/modtool/gr-newmod/docs/doxygen/swig_doc.py b/gr-utils/python/modtool/gr-newmod/docs/doxygen/swig_doc.py
index 9079a33c4f..07c5b75401 100644
--- a/gr-utils/python/modtool/gr-newmod/docs/doxygen/swig_doc.py
+++ b/gr-utils/python/modtool/gr-newmod/docs/doxygen/swig_doc.py
@@ -27,6 +27,7 @@ The file instructs SWIG to transfer the doxygen comments into the
python docstrings.
"""
+from __future__ import unicode_literals
import sys, time
@@ -310,7 +311,7 @@ if __name__ == "__main__":
# Parse command line options and set up doxyxml.
err_msg = "Execute using: python swig_doc.py xml_path outputfilename"
if len(sys.argv) != 3:
- raise StandardError(err_msg)
+ raise Exception(err_msg)
xml_path = sys.argv[1]
swigdocfilename = sys.argv[2]
di = DoxyIndex(xml_path)
diff --git a/gr-utils/python/modtool/gr-newmod/lib/CMakeLists.txt b/gr-utils/python/modtool/gr-newmod/lib/CMakeLists.txt
index e932a95e48..64b7c1d4ab 100644
--- a/gr-utils/python/modtool/gr-newmod/lib/CMakeLists.txt
+++ b/gr-utils/python/modtool/gr-newmod/lib/CMakeLists.txt
@@ -49,7 +49,7 @@ endif(APPLE)
# Install built library files
########################################################################
include(GrMiscUtils)
-GR_LIBRARY_FOO(gnuradio-howto RUNTIME_COMPONENT "howto_runtime" DEVEL_COMPONENT "howto_devel")
+GR_LIBRARY_FOO(gnuradio-howto)
########################################################################
# Build and register unit test
@@ -80,4 +80,3 @@ GR_ADD_TEST(test_howto test-howto)
########################################################################
message(STATUS "Using install prefix: ${CMAKE_INSTALL_PREFIX}")
message(STATUS "Building for version: ${VERSION} / ${LIBVER}")
-
diff --git a/gr-utils/python/modtool/gr-newmod/python/__init__.py b/gr-utils/python/modtool/gr-newmod/python/__init__.py
index ed385a0abe..806f287cc3 100644
--- a/gr-utils/python/modtool/gr-newmod/python/__init__.py
+++ b/gr-utils/python/modtool/gr-newmod/python/__init__.py
@@ -22,6 +22,7 @@
This is the GNU Radio HOWTO module. Place your Python package
description here (python/__init__.py).
'''
+from __future__ import unicode_literals
# import swig generated symbols into the howto namespace
try:
diff --git a/gr-utils/python/modtool/gr-newmod/python/build_utils.py b/gr-utils/python/modtool/gr-newmod/python/build_utils.py
deleted file mode 100644
index 01fcf3bc88..0000000000
--- a/gr-utils/python/modtool/gr-newmod/python/build_utils.py
+++ /dev/null
@@ -1,228 +0,0 @@
-#
-# Copyright 2004,2009,2012 Free Software Foundation, Inc.
-#
-# This file was generated by gr_modtool, a tool from the GNU Radio framework
-# This file is a part of gr-howto
-#
-# GNU Radio is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 3, or (at your option)
-# any later version.
-#
-# GNU Radio is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with GNU Radio; see the file COPYING. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street,
-# Boston, MA 02110-1301, USA.
-#
-
-"""Misc utilities used at build time
-"""
-
-import re
-import os
-import os.path
-from build_utils_codes import *
-
-
-# set srcdir to the directory that contains Makefile.am
-try:
- srcdir = os.environ['srcdir']
-except KeyError, e:
- srcdir = "."
-srcdir = srcdir + '/'
-
-# set do_makefile to either true or false dependeing on the environment
-try:
- if os.environ['do_makefile'] == '0':
- do_makefile = False
- else:
- do_makefile = True
-except KeyError, e:
- do_makefile = False
-
-# set do_sources to either true or false dependeing on the environment
-try:
- if os.environ['do_sources'] == '0':
- do_sources = False
- else:
- do_sources = True
-except KeyError, e:
- do_sources = True
-
-name_dict = {}
-
-def log_output_name(name):
- (base, ext) = os.path.splitext(name)
- ext = ext[1:] # drop the leading '.'
-
- entry = name_dict.setdefault(ext, [])
- entry.append(name)
-
-def open_and_log_name(name, dir):
- global do_sources
- if do_sources:
- f = open(name, dir)
- else:
- f = None
- log_output_name(name)
- return f
-
-def expand_template(d, template_filename, extra=""):
- '''Given a dictionary D and a TEMPLATE_FILENAME, expand template into output file
- '''
- global do_sources
- output_extension = extract_extension(template_filename)
- template = open_src(template_filename, 'r')
- output_name = d['NAME'] + extra + '.' + output_extension
- log_output_name(output_name)
- if do_sources:
- output = open(output_name, 'w')
- do_substitution(d, template, output)
- output.close()
- template.close()
-
-def output_glue(dirname):
- output_makefile_fragment()
- output_ifile_include(dirname)
-
-def output_makefile_fragment():
- global do_makefile
- if not do_makefile:
- return
-# overwrite the source, which must be writable; this should have been
-# checked for beforehand in the top-level Makefile.gen.gen .
- f = open(os.path.join(os.environ.get('gendir', os.environ.get('srcdir', '.')), 'Makefile.gen'), 'w')
- f.write('#\n# This file is machine generated. All edits will be overwritten\n#\n')
- output_subfrag(f, 'h')
- output_subfrag(f, 'i')
- output_subfrag(f, 'cc')
- f.close()
-
-def output_ifile_include(dirname):
- global do_sources
- if do_sources:
- f = open('%s_generated.i' % (dirname,), 'w')
- f.write('//\n// This file is machine generated. All edits will be overwritten\n//\n')
- files = name_dict.setdefault('i', [])
- files.sort()
- f.write('%{\n')
- for file in files:
- f.write('#include <%s>\n' % (file[0:-1] + 'h',))
- f.write('%}\n\n')
- for file in files:
- f.write('%%include <%s>\n' % (file,))
-
-def output_subfrag(f, ext):
- files = name_dict.setdefault(ext, [])
- files.sort()
- f.write("GENERATED_%s =" % (ext.upper()))
- for file in files:
- f.write(" \\\n\t%s" % (file,))
- f.write("\n\n")
-
-def extract_extension(template_name):
- # template name is something like: GrFIRfilterXXX.h.t
- # 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,)
- return mo.group(1)
-
-def open_src(name, mode):
- global srcdir
- return open(os.path.join(srcdir, name), mode)
-
-def do_substitution(d, in_file, out_file):
- def repl(match_obj):
- key = match_obj.group(1)
- # print key
- return d[key]
-
- inp = in_file.read()
- out = re.sub(r"@([a-zA-Z0-9_]+)@", repl, inp)
- out_file.write(out)
-
-
-
-copyright = '''/* -*- c++ -*- */
-/*
- * Copyright 2003,2004 Free Software Foundation, Inc.
- *
- * This file is part of GNU Radio
- *
- * GNU Radio is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 3, or (at your option)
- * any later version.
- *
- * GNU Radio is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with GNU Radio; see the file COPYING. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street,
- * Boston, MA 02110-1301, USA.
- */
-'''
-
-def is_complex(code3):
- if i_code(code3) == 'c' or o_code(code3) == 'c':
- return '1'
- return '0'
-
-
-def standard_dict(name, code3, package='gr'):
- d = {}
- d['NAME'] = name
- d['NAME_IMPL'] = name+'_impl'
- d['GUARD_NAME'] = 'INCLUDED_%s_%s_H' % (package.upper(), name.upper())
- d['GUARD_NAME_IMPL'] = 'INCLUDED_%s_%s_IMPL_H' % (package.upper(), name.upper())
- d['BASE_NAME'] = re.sub('^' + package + '_', '', name)
- d['SPTR_NAME'] = '%s_sptr' % name
- d['WARNING'] = 'WARNING: this file is machine generated. Edits will be overwritten'
- d['COPYRIGHT'] = copyright
- d['TYPE'] = i_type(code3)
- d['I_TYPE'] = i_type(code3)
- d['O_TYPE'] = o_type(code3)
- d['TAP_TYPE'] = tap_type(code3)
- d['IS_COMPLEX'] = is_complex(code3)
- return d
-
-
-def standard_dict2(name, code3, package):
- d = {}
- d['NAME'] = name
- d['BASE_NAME'] = name
- d['GUARD_NAME'] = 'INCLUDED_%s_%s_H' % (package.upper(), name.upper())
- d['WARNING'] = 'WARNING: this file is machine generated. Edits will be overwritten'
- d['COPYRIGHT'] = copyright
- d['TYPE'] = i_type(code3)
- d['I_TYPE'] = i_type(code3)
- d['O_TYPE'] = o_type(code3)
- d['TAP_TYPE'] = tap_type(code3)
- d['IS_COMPLEX'] = is_complex(code3)
- return d
-
-def standard_impl_dict2(name, code3, package):
- d = {}
- d['NAME'] = name
- d['IMPL_NAME'] = name
- d['BASE_NAME'] = name.rstrip("impl").rstrip("_")
- d['GUARD_NAME'] = 'INCLUDED_%s_%s_H' % (package.upper(), name.upper())
- d['WARNING'] = 'WARNING: this file is machine generated. Edits will be overwritten'
- d['COPYRIGHT'] = copyright
- d['FIR_TYPE'] = "fir_filter_" + code3
- d['CFIR_TYPE'] = "fir_filter_" + code3[0:2] + 'c'
- d['TYPE'] = i_type(code3)
- d['I_TYPE'] = i_type(code3)
- d['O_TYPE'] = o_type(code3)
- d['TAP_TYPE'] = tap_type(code3)
- d['IS_COMPLEX'] = is_complex(code3)
- return d
diff --git a/gr-utils/python/modtool/gr-newmod/python/build_utils_codes.py b/gr-utils/python/modtool/gr-newmod/python/build_utils_codes.py
deleted file mode 100644
index 2e4f2aa653..0000000000
--- a/gr-utils/python/modtool/gr-newmod/python/build_utils_codes.py
+++ /dev/null
@@ -1,51 +0,0 @@
-#
-# Copyright 2004 Free Software Foundation, Inc.
-#
-# This file was generated by gr_modtool, a tool from the GNU Radio framework
-# This file is a part of gr-howto
-#
-# GNU Radio is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 3, or (at your option)
-# any later version.
-#
-# GNU Radio is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with GNU Radio; see the file COPYING. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street,
-# Boston, MA 02110-1301, USA.
-#
-
-def i_code(code3):
- return code3[0]
-
-def o_code(code3):
- if len(code3) >= 2:
- return code3[1]
- return code3[0]
-
-def tap_code(code3):
- if len(code3) >= 3:
- return code3[2]
- return code3[0]
-
-def i_type(code3):
- return char_to_type[i_code(code3)]
-
-def o_type(code3):
- return char_to_type[o_code(code3)]
-
-def tap_type(code3):
- return char_to_type[tap_code(code3)]
-
-
-char_to_type = {}
-char_to_type['s'] = 'short'
-char_to_type['i'] = 'int'
-char_to_type['f'] = 'float'
-char_to_type['c'] = 'gr_complex'
-char_to_type['b'] = 'unsigned char'
diff --git a/gr-utils/python/modtool/grc_xml_generator.py b/gr-utils/python/modtool/grc_xml_generator.py
index af17ca1822..1109701f7e 100644
--- a/gr-utils/python/modtool/grc_xml_generator.py
+++ b/gr-utils/python/modtool/grc_xml_generator.py
@@ -1,3 +1,4 @@
+from __future__ import absolute_import
#
# Copyright 2013 Free Software Foundation, Inc.
#
@@ -19,7 +20,7 @@
# Boston, MA 02110-1301, USA.
#
import xml.etree.ElementTree as ET
-from util_functions import is_number, xml_indent
+from .util_functions import is_number, xml_indent
try:
import lxml.etree
diff --git a/gr-utils/python/modtool/modtool_add.py b/gr-utils/python/modtool/modtool_add.py
index c7486c0a7c..46ff74168a 100644
--- a/gr-utils/python/modtool/modtool_add.py
+++ b/gr-utils/python/modtool/modtool_add.py
@@ -20,24 +20,23 @@
#
""" Module to add new blocks """
+from __future__ import print_function
+from __future__ import absolute_import
+from __future__ import unicode_literals
+
import os
import re
-from optparse import OptionGroup
-import getpass
-import readline
-import Cheetah.Template
-
-from util_functions import append_re_line_sequence, ask_yes_no, SequenceCompleter
-from cmakefile_editor import CMakeFileEditor
-from modtool_base import ModTool, ModToolException
-from templates import Templates
-from code_generator import get_template
+from .util_functions import append_re_line_sequence, ask_yes_no, SequenceCompleter
+from .cmakefile_editor import CMakeFileEditor
+from .modtool_base import ModTool, ModToolException
+from .templates import Templates
+from .code_generator import render_template
class ModToolAdd(ModTool):
""" Add block to the out-of-tree module. """
name = 'add'
- aliases = ('insert',)
+ description = 'Add new block into module.'
_block_types = ('sink', 'source', 'sync', 'decimator', 'interpolator',
'general', 'tagged_stream', 'hier', 'noblock')
@@ -48,31 +47,29 @@ class ModToolAdd(ModTool):
self._skip_cmakefiles = False
self._license_file = None
- def setup_parser(self):
- parser = ModTool.setup_parser(self)
- ogroup = OptionGroup(parser, "Add module options")
- ogroup.add_option("-t", "--block-type", type="choice",
- choices=self._block_types, default=None,
- help="One of %s." % ', '.join(self._block_types))
- ogroup.add_option("--license-file", type="string", default=None,
- help="File containing the license header for every source code file.")
- ogroup.add_option("--copyright", type="string", default=None,
- help="Name of the copyright holder (you or your company) MUST be a quoted string.")
- ogroup.add_option("--argument-list", type="string", default=None,
- help="The argument list for the constructor and make functions.")
- ogroup.add_option("--add-python-qa", action="store_true", default=None,
- help="If given, Python QA code is automatically added if possible.")
- ogroup.add_option("--add-cpp-qa", action="store_true", default=None,
- help="If given, C++ QA code is automatically added if possible.")
- ogroup.add_option("--skip-cmakefiles", action="store_true", default=False,
- help="If given, only source files are written, but CMakeLists.txt files are left unchanged.")
- ogroup.add_option("-l", "--lang", type="choice", choices=('cpp', 'c++', 'python'),
- default=None, help="Language (cpp or python)")
- parser.add_option_group(ogroup)
+ @staticmethod
+ def setup_parser(parser):
+ parser.add_argument("-t", "--block-type", choices=ModToolAdd._block_types,
+ help="One of %s." % ', '.join(ModToolAdd._block_types))
+ parser.add_argument("--license-file",
+ help="File containing the license header for every source code file.")
+ parser.add_argument("--copyright",
+ help="Name of the copyright holder (you or your company) MUST be a quoted string.")
+ parser.add_argument("--argument-list",
+ help="The argument list for the constructor and make functions.")
+ parser.add_argument("--add-python-qa", action="store_true", default=None,
+ help="If given, Python QA code is automatically added if possible.")
+ parser.add_argument("--add-cpp-qa", action="store_true", default=None,
+ help="If given, C++ QA code is automatically added if possible.")
+ parser.add_argument("--skip-cmakefiles", action="store_true",
+ help="If given, only source files are written, but CMakeLists.txt files are left unchanged.")
+ parser.add_argument("-l", "--lang", choices=('cpp', 'c++', 'python'),
+ help="Programing language")
+ ModTool.setup_parser_block(parser)
return parser
- def setup(self, options, args):
- ModTool.setup(self, options, args)
+ def setup(self, options):
+ ModTool.setup(self, options)
if self._info['blockname'] is None:
if len(args) >= 2:
@@ -89,29 +86,35 @@ class ModToolAdd(ModTool):
self._info['blocktype'] = options.block_type
if self._info['blocktype'] is None:
# Print list out of blocktypes to user for reference
- print str(self._block_types)
+ print(str(self._block_types))
with SequenceCompleter(sorted(self._block_types)):
while self._info['blocktype'] not in self._block_types:
- self._info['blocktype'] = raw_input("Enter block type: ")
+ self._info['blocktype'] = input("Enter block type: ")
if self._info['blocktype'] not in self._block_types:
- print 'Must be one of ' + str(self._block_types)
+ print('Must be one of ' + str(self._block_types))
# Allow user to specify language interactively if not set
self._info['lang'] = options.lang
if self._info['lang'] is None:
- language_candidates = ('cpp', 'python')
+ language_candidates = ('c++', 'cpp', 'python')
with SequenceCompleter(language_candidates):
while self._info['lang'] not in language_candidates:
- self._info['lang'] = raw_input("Language (python/cpp): ")
+ self._info['lang'] = input("Language (python/cpp): ")
if self._info['lang'] == 'c++':
self._info['lang'] = 'cpp'
- print "Language: %s" % {'cpp': 'C++', 'python': 'Python'}[self._info['lang']]
+ print("Language: %s" % {'cpp': 'C++', 'python': 'Python'}[self._info['lang']])
if ((self._skip_subdirs['lib'] and self._info['lang'] == 'cpp')
or (self._skip_subdirs['python'] and self._info['lang'] == 'python')):
raise ModToolException('Missing or skipping relevant subdir.')
+ if self._info['blockname'] is None:
+ self._info['blockname'] = input("Enter name of block/code (without module name prefix): ")
+ if not re.match('[a-zA-Z0-9_]+', self._info['blockname']):
+ raise ModToolException('Invalid block name.')
+ print("Block/code identifier: " + self._info['blockname'])
+ self._info['fullblockname'] = self._info['modname'] + '_' + self._info['blockname']
if not options.license_file:
self._info['copyrightholder'] = options.copyright
if self._info['copyrightholder'] is None:
@@ -126,13 +129,13 @@ class ModToolAdd(ModTool):
if not self._info['copyrightholder'] or self._info['copyrightholder'].isspace():
self._info['copyrightholder'] = "gr-"+self._info['modname']+" author"
elif self._info['is_component']:
- print "For GNU Radio components the FSF is added as copyright holder"
+ print("For GNU Radio components the FSF is added as copyright holder")
self._license_file = options.license_file
self._info['license'] = self.setup_choose_license()
if options.argument_list is not None:
self._info['arglist'] = options.argument_list
else:
- self._info['arglist'] = raw_input('Enter valid argument list, including default arguments: ')
+ self._info['arglist'] = input('Enter valid argument list, including default arguments: ')
if not (self._info['blocktype'] in ('noblock') or self._skip_subdirs['python']):
self._add_py_qa = options.add_python_qa
@@ -144,8 +147,8 @@ class ModToolAdd(ModTool):
self._add_cc_qa = ask_yes_no('Add C++ QA code?', not self._add_py_qa)
self._skip_cmakefiles = options.skip_cmakefiles
if self._info['version'] == 'autofoo' and not self._skip_cmakefiles:
- print "Warning: Autotools modules are not supported. ",
- print "Files will be created, but Makefiles will not be edited."
+ print("Warning: Autotools modules are not supported. ",
+ "Files will be created, but Makefiles will not be edited.")
self._skip_cmakefiles = True
def setup_choose_license(self):
@@ -163,17 +166,19 @@ class ModToolAdd(ModTool):
return open('LICENCE').read()
elif self._info['is_component']:
return Templates['grlicense']
- return get_template('defaultlicense', **self._info)
+ else:
+ return Templates['defaultlicense'].format(**self._info)
def _write_tpl(self, tpl, path, fname):
""" Shorthand for writing a substituted template to a file"""
path_to_file = os.path.join(path, fname)
- print "Adding file '%s'..." % path_to_file
- open(path_to_file, 'w').write(get_template(tpl, **self._info))
+ print("Adding file '%s'..." % path_to_file)
+ open(path_to_file, 'w').write(render_template(tpl, **self._info))
self.scm.add_files((path_to_file,))
- def run(self):
+ def run(self, options):
""" Go, go, go. """
+ self.setup(options)
has_swig = (
self._info['lang'] == 'cpp'
and not self._skip_subdirs['swig']
@@ -221,27 +226,7 @@ class ModToolAdd(ModTool):
)
self.scm.mark_files_updated((self._file['qalib'],))
except IOError:
- print "Can't add C++ QA files."
- def _add_qa36():
- " Add C++ QA files for pre-3.7 API (not autotools) "
- fname_qa_cc = 'qa_%s.cc' % self._info['fullblockname']
- self._write_tpl('qa_cpp36', 'lib', fname_qa_cc)
- if not self._skip_cmakefiles:
- open(self._file['cmlib'], 'a').write(
- str(
- Cheetah.Template.Template(
- Templates['qa_cmakeentry36'],
- searchList={'basename': os.path.splitext(fname_qa_cc)[0],
- 'upperbasename': os.path.splitext(fname_qa_cc)[0].upper(),
- 'filename': fname_qa_cc,
- 'modname': self._info['modname']
- }
- )
- )
- )
- ed = CMakeFileEditor(self._file['cmlib'])
- ed.remove_double_newlines()
- ed.write()
+ print("Can't add C++ QA files.")
fname_cc = None
fname_h = None
if self._info['version'] == '37':
@@ -262,9 +247,9 @@ class ModToolAdd(ModTool):
if self._info['version'] == '37':
_add_qa()
elif self._info['version'] == '36':
- _add_qa36()
+ print("Warning: C++ QA files not supported for 3.6-style OOTs.")
elif self._info['version'] == 'autofoo':
- print "Warning: C++ QA files not supported for autotools."
+ print("Warning: C++ QA files not supported for autotools.")
if not self._skip_cmakefiles:
ed = CMakeFileEditor(self._file['cmlib'])
cmake_list_var = '[a-z]*_?' + self._info['modname'] + '_sources'
@@ -281,13 +266,13 @@ class ModToolAdd(ModTool):
- Edit main *.i file
"""
if self._get_mainswigfile() is None:
- print 'Warning: No main swig file found.'
+ print('Warning: No main swig file found.')
return
- print "Editing %s..." % self._file['swig']
+ print("Editing %s..." % self._file['swig'])
mod_block_sep = '/'
if self._info['version'] == '36':
mod_block_sep = '_'
- swig_block_magic_str = get_template('swig_block_magic', **self._info)
+ swig_block_magic_str = render_template('swig_block_magic', **self._info)
open(self._file['swig'], 'a').write(swig_block_magic_str)
include_str = '#include "%s%s%s.h"' % (
{True: 'gnuradio/' + self._info['modname'],
@@ -311,11 +296,11 @@ class ModToolAdd(ModTool):
"""
fname_py_qa = 'qa_' + self._info['blockname'] + '.py'
self._write_tpl('qa_python', self._info['pydir'], fname_py_qa)
- os.chmod(os.path.join(self._info['pydir'], fname_py_qa), 0755)
+ os.chmod(os.path.join(self._info['pydir'], fname_py_qa), 0o755)
self.scm.mark_files_updated((os.path.join(self._info['pydir'], fname_py_qa),))
if self._skip_cmakefiles or CMakeFileEditor(self._file['cmpython']).check_for_glob('qa_*.py'):
return
- print "Editing %s/CMakeLists.txt..." % self._info['pydir']
+ print("Editing %s/CMakeLists.txt..." % self._info['pydir'])
open(self._file['cmpython'], 'a').write(
'GR_ADD_TEST(qa_%s ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/%s)\n' % \
(self._info['blockname'], fname_py_qa))
@@ -353,7 +338,7 @@ class ModToolAdd(ModTool):
ed = CMakeFileEditor(self._file['cmgrc'], '\n ')
if self._skip_cmakefiles or ed.check_for_glob('*.xml'):
return
- print "Editing grc/CMakeLists.txt..."
+ print("Editing grc/CMakeLists.txt...")
ed.append_value('install', fname_grc, to_ignore_end='DESTINATION[^()]+')
ed.write()
self.scm.mark_files_updated((self._file['cmgrc'],))
diff --git a/gr-utils/python/modtool/modtool_base.py b/gr-utils/python/modtool/modtool_base.py
index 0bbd95946d..4263e498f7 100644
--- a/gr-utils/python/modtool/modtool_base.py
+++ b/gr-utils/python/modtool/modtool_base.py
@@ -20,13 +20,17 @@
#
""" Base class for the modules """
+from __future__ import print_function
+from __future__ import absolute_import
+from __future__ import unicode_literals
+
import os
import re
-from optparse import OptionParser, OptionGroup
+from argparse import ArgumentParser, RawDescriptionHelpFormatter
from gnuradio import gr
-from util_functions import get_modname
-from scm import SCMRepoFactory
+from .util_functions import get_modname
+from .scm import SCMRepoFactory
class ModToolException(BaseException):
""" Standard exception for modtool classes. """
@@ -35,6 +39,8 @@ class ModToolException(BaseException):
class ModTool(object):
""" Base class for all modtool command classes. """
name = 'base'
+ description = None
+
def __init__(self):
self._subdirs = ['lib', 'include', 'python', 'swig', 'grc'] # List subdirs where stuff happens
self._has_subdirs = {}
@@ -44,52 +50,56 @@ class ModTool(object):
for subdir in self._subdirs:
self._has_subdirs[subdir] = False
self._skip_subdirs[subdir] = False
- self.parser = self.setup_parser()
self._dir = None
self.scm = None
- def setup_parser(self):
- """ Init the option parser. If derived classes need to add options,
- override this and call the parent function. """
- parser = OptionParser(add_help_option=False)
- parser.usage = '%prog ' + self.name + ' [options] <PATTERN> \n' + \
- ' Call "%prog ' + self.name + '" without any options to run it interactively.'
- ogroup = OptionGroup(parser, "General options")
- ogroup.add_option("-h", "--help", action="help", help="Displays this help message.")
- ogroup.add_option("-d", "--directory", type="string", default=".",
- help="Base directory of the module. Defaults to the cwd.")
- ogroup.add_option("-n", "--module-name", type="string", default=None,
- help="Use this to override the current module's name (is normally autodetected).")
- ogroup.add_option("-N", "--block-name", type="string", default=None,
- help="Name of the block, where applicable.")
- ogroup.add_option("--skip-lib", action="store_true", default=False,
- help="Don't do anything in the lib/ subdirectory.")
- ogroup.add_option("--skip-swig", action="store_true", default=False,
- help="Don't do anything in the swig/ subdirectory.")
- ogroup.add_option("--skip-python", action="store_true", default=False,
- help="Don't do anything in the python/ subdirectory.")
- ogroup.add_option("--skip-grc", action="store_true", default=False,
- help="Don't do anything in the grc/ subdirectory.")
- ogroup.add_option("--scm-mode", type="choice", choices=('yes', 'no', 'auto'),
- default=gr.prefs().get_string('modtool', 'scm_mode', 'no'),
- help="Use source control management (yes, no or auto).")
- ogroup.add_option("-y", "--yes", action="store_true", default=False,
- help="Answer all questions with 'yes'. This can overwrite and delete your files, so be careful.")
- parser.add_option_group(ogroup)
+ @staticmethod
+ def setup_parser(parser):
+ """Override in child class."""
+ pass
+
+ @staticmethod
+ def setup_parser_block(parser):
+ """Setup options specific for block manipulating modules."""
+ parser.add_argument("blockname", nargs="?", metavar="BLOCK_NAME",
+ help="Name of the block/module")
+
+ @staticmethod
+ def get_parser():
+ """Init the option parser."""
+ parser = ArgumentParser(
+ description='Manipulate with GNU Radio modules source code tree. ' + \
+ 'Call it withou options to run specified command interactively',
+ formatter_class=RawDescriptionHelpFormatter)
+ parser.add_argument("-d", "--directory", default=".",
+ help="Base directory of the module. Defaults to the cwd.")
+ parser.add_argument("--skip-lib", action="store_true",
+ help="Don't do anything in the lib/ subdirectory.")
+ parser.add_argument("--skip-swig", action="store_true",
+ help="Don't do anything in the swig/ subdirectory.")
+ parser.add_argument("--skip-python", action="store_true",
+ help="Don't do anything in the python/ subdirectory.")
+ parser.add_argument("--skip-grc", action="store_true",
+ help="Don't do anything in the grc/ subdirectory.")
+ parser.add_argument("--scm-mode", choices=('yes', 'no', 'auto'),
+ default=gr.prefs().get_string('modtool', 'scm_mode', 'no'),
+ help="Use source control management [ yes | no | auto ]).")
+ parser.add_argument("-y", "--yes", action="store_true",
+ help="Answer all questions with 'yes'. This can overwrite and delete your files, so be careful.")
return parser
- def setup(self, options, args):
+ def setup(self, options):
""" Initialise all internal variables, such as the module name etc. """
self._dir = options.directory
if not self._check_directory(self._dir):
raise ModToolException('No GNU Radio module found in the given directory.')
- if options.module_name is not None:
+ if hasattr(options, 'module_name') and options.module_name is not None:
self._info['modname'] = options.module_name
else:
self._info['modname'] = get_modname()
if self._info['modname'] is None:
raise ModToolException('No GNU Radio module found in the given directory.')
- print "GNU Radio module name identified: " + self._info['modname']
+ print("GNU Radio module name identified: " + self._info['modname'])
if self._info['version'] == '36' and (
os.path.isdir(os.path.join('include', self._info['modname'])) or
os.path.isdir(os.path.join('include', 'gnuradio', self._info['modname']))
@@ -103,7 +113,7 @@ class ModTool(object):
self._skip_subdirs['swig'] = True
if options.skip_grc or not self._has_subdirs['grc']:
self._skip_subdirs['grc'] = True
- self._info['blockname'] = options.block_name
+ self._info['blockname'] = options.blockname
self._setup_files()
self._info['yes'] = options.yes
self.options = options
@@ -139,7 +149,7 @@ class ModTool(object):
else:
self.scm = SCMRepoFactory(self.options, '.').make_empty_scm_manager()
if self.scm is None:
- print "Error: Can't set up SCM."
+ print("Error: Can't set up SCM.")
exit(1)
def _check_directory(self, directory):
@@ -151,7 +161,7 @@ class ModTool(object):
files = os.listdir(directory)
os.chdir(directory)
except OSError:
- print "Can't read or chdir to directory %s." % directory
+ print("Can't read or chdir to directory %s." % directory)
return False
self._info['is_component'] = False
for f in files:
@@ -165,11 +175,11 @@ class ModTool(object):
has_makefile = True
# TODO search for autofoo
elif os.path.isdir(f):
- if f in self._has_subdirs.keys():
+ if (f in list(self._has_subdirs.keys())):
self._has_subdirs[f] = True
else:
self._skip_subdirs[f] = True
- return bool(has_makefile and (self._has_subdirs.values()))
+ return bool(has_makefile and (list(self._has_subdirs.values())))
def _get_mainswigfile(self):
""" Find out which name the main SWIG file has. In particular, is it
@@ -182,20 +192,19 @@ class ModTool(object):
return fname
return None
- def run(self):
+ def run(self, options):
""" Override this. """
- pass
+ raise NotImplementedError('Module implementation missing')
-def get_class_dict(the_globals):
- " Return a dictionary of the available commands in the form command->class "
- classdict = {}
- for g in the_globals:
+def get_modtool_modules(all_objects):
+ """Return list with all modtool modules."""
+ modules = []
+ for o in all_objects:
try:
- if issubclass(g, ModTool):
- classdict[g.name] = g
- for alias in g.aliases:
- classdict[alias] = g
+ if issubclass(o, ModTool) and o != ModTool:
+ modules.append(o)
except (TypeError, AttributeError):
pass
- return classdict
+ return modules
+
diff --git a/gr-utils/python/modtool/modtool_disable.py b/gr-utils/python/modtool/modtool_disable.py
index a23e16eccb..556b2e1ab2 100644
--- a/gr-utils/python/modtool/modtool_disable.py
+++ b/gr-utils/python/modtool/modtool_disable.py
@@ -20,35 +20,41 @@
#
""" Disable blocks module """
+from __future__ import print_function
+from __future__ import absolute_import
+from __future__ import unicode_literals
+
import os
import re
import sys
-from modtool_base import ModTool
-from cmakefile_editor import CMakeFileEditor
+from .modtool_base import ModTool
+from .cmakefile_editor import CMakeFileEditor
class ModToolDisable(ModTool):
""" Disable block (comments out CMake entries for files) """
name = 'disable'
- aliases = ('dis',)
+ description = 'Disable selected block in module.'
def __init__(self):
ModTool.__init__(self)
- def setup(self, options, args):
- ModTool.setup(self, options, args)
+ @staticmethod
+ def setup_parser(parser):
+ ModTool.setup_parser_block(parser)
+
+ def setup(self, options):
+ ModTool.setup(self, options)
- if options.block_name is not None:
- self._info['pattern'] = options.block_name
- elif len(args) >= 2:
- self._info['pattern'] = args[1]
+ if options.blockname is not None:
+ self._info['pattern'] = options.blockname
else:
- self._info['pattern'] = raw_input('Which blocks do you want to disable? (Regex): ')
- if not self._info['pattern'] or self._info['pattern'].isspace():
+ self._info['pattern'] = input('Which blocks do you want to disable? (Regex): ')
+ if len(self._info['pattern']) == 0:
self._info['pattern'] = '.'
- def run(self):
+ def run(self, options):
""" Go, go, go! """
def _handle_py_qa(cmake, fname):
""" Do stuff for py qa """
@@ -60,7 +66,7 @@ class ModToolDisable(ModTool):
try:
initfile = open(self._file['pyinit']).read()
except IOError:
- print "Could not edit __init__.py, that might be a problem."
+ print("Could not edit __init__.py, that might be a problem.")
return False
pymodname = os.path.splitext(fname)[0]
initfile = re.sub(r'((from|import)\s+\b'+pymodname+r'\b)', r'#\1', initfile)
@@ -90,14 +96,14 @@ class ModToolDisable(ModTool):
(swigfile, nsubs) = re.subn(r'(.include\s+"(%s/)?%s")' % (
self._info['modname'], fname), r'//\1', swigfile)
if nsubs > 0:
- print "Changing %s..." % self._file['swig']
+ print("Changing %s..." % self._file['swig'])
if nsubs > 1: # Need to find a single BLOCK_MAGIC
blockname = os.path.splitext(fname[len(self._info['modname'])+1:])[0]
if self._info['version'] == '37':
blockname = os.path.splitext(fname)[0]
(swigfile, nsubs) = re.subn('(GR_SWIG_BLOCK_MAGIC2?.+%s.+;)' % blockname, r'//\1', swigfile)
if nsubs > 1:
- print "Hm, changed more then expected while editing %s." % self._file['swig']
+ print("Hm, changed more then expected while editing %s." % self._file['swig'])
open(self._file['swig'], 'w').write(swigfile)
self.scm.mark_file_updated(self._file['swig'])
return False
@@ -108,12 +114,13 @@ class ModToolDisable(ModTool):
blockname = os.path.splitext(fname[len(self._info['modname'])+1:])[0]
if self._info['version'] == '37':
blockname = os.path.splitext(fname)[0]
- swigfile = re.sub(r'(%include\s+"'+fname+'")', r'//\1', swigfile)
- print "Changing %s..." % self._file['swig']
+ swigfile = re.sub('(%include\s+"'+fname+'")', r'//\1', swigfile)
+ print("Changing %s..." % self._file['swig'])
swigfile = re.sub('(GR_SWIG_BLOCK_MAGIC2?.+'+blockname+'.+;)', r'//\1', swigfile)
open(self._file['swig'], 'w').write(swigfile)
self.scm.mark_file_updated(self._file['swig'])
return False
+ self.setup(options)
# List of special rules: 0: subdir, 1: filename re match, 2: callback
special_treatments = (
('python', r'qa.+py$', _handle_py_qa),
@@ -132,13 +139,13 @@ class ModToolDisable(ModTool):
cmake = CMakeFileEditor(os.path.join(subdir, 'CMakeLists.txt'))
except IOError:
continue
- print "Traversing %s..." % subdir
+ print("Traversing %s..." % subdir)
filenames = cmake.find_filenames_match(self._info['pattern'])
yes = self._info['yes']
for fname in filenames:
file_disabled = False
if not yes:
- ans = raw_input("Really disable %s? [Y/n/a/q]: " % fname).lower().strip()
+ ans = input("Really disable %s? [Y/n/a/q]: " % fname).lower().strip()
if ans == 'a':
yes = True
if ans == 'q':
@@ -152,4 +159,5 @@ class ModToolDisable(ModTool):
cmake.disable_file(fname)
cmake.write()
self.scm.mark_files_updated((os.path.join(subdir, 'CMakeLists.txt'),))
- print "Careful: 'gr_modtool disable' does not resolve dependencies."
+ print("Careful: 'gr_modtool disable' does not resolve dependencies.")
+
diff --git a/gr-utils/python/modtool/modtool_help.py b/gr-utils/python/modtool/modtool_help.py
deleted file mode 100644
index 6c7a62e891..0000000000
--- a/gr-utils/python/modtool/modtool_help.py
+++ /dev/null
@@ -1,67 +0,0 @@
-#
-# Copyright 2013 Free Software Foundation, Inc.
-#
-# This file is part of GNU Radio
-#
-# GNU Radio is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 3, or (at your option)
-# any later version.
-#
-# GNU Radio is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with GNU Radio; see the file COPYING. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street,
-# Boston, MA 02110-1301, USA.
-#
-""" The help module """
-
-from gnuradio.modtool import *
-from util_functions import get_command_from_argv
-from templates import Templates
-
-
-def print_class_descriptions():
- """ Go through all ModTool* classes and print their name,
- alias and description. """
- desclist = []
- for gvar in globals().values():
- try:
- if issubclass(gvar, ModTool) and not issubclass(gvar, ModToolHelp):
- desclist.append((gvar.name, ','.join(gvar.aliases), gvar.__doc__))
- except (TypeError, AttributeError):
- pass
- print 'Name Aliases Description'
- print '====================================================================='
- for description in desclist:
- print '%-8s %-12s %s' % description
-
-
-class ModToolHelp(ModTool):
- """ Show some help. """
- name = 'help'
- aliases = ('h', '?')
-
- def __init__(self):
- ModTool.__init__(self)
-
- def setup(self, options, args):
- pass
-
- def run(self):
- cmd_dict = get_class_dict(globals().values())
- cmds = cmd_dict.keys()
- cmds.remove(self.name)
- for a in self.aliases:
- cmds.remove(a)
- help_requested_for = get_command_from_argv(cmds)
- if help_requested_for is None:
- print 'Usage:' + Templates['usage']
- print '\nList of possible commands:\n'
- print_class_descriptions()
- return
- cmd_dict[help_requested_for]().setup_parser().print_help()
diff --git a/gr-utils/python/modtool/modtool_info.py b/gr-utils/python/modtool/modtool_info.py
index 3380760725..bae6df36ed 100644
--- a/gr-utils/python/modtool/modtool_info.py
+++ b/gr-utils/python/modtool/modtool_info.py
@@ -1,4 +1,3 @@
-#
# Copyright 2013 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
@@ -20,17 +19,20 @@
#
""" Returns information about a module """
+from __future__ import print_function
+from __future__ import absolute_import
+from __future__ import unicode_literals
+
import os
-from optparse import OptionGroup
-from modtool_base import ModTool, ModToolException
-from util_functions import get_modname
+from .modtool_base import ModTool, ModToolException
+from .util_functions import get_modname
class ModToolInfo(ModTool):
""" Return information about a given module """
name = 'info'
- aliases = ('getinfo', 'inf')
+ description = 'Return informations about module.'
def __init__(self):
ModTool.__init__(self)
@@ -38,26 +40,25 @@ class ModToolInfo(ModTool):
self._python_readable = False
self._suggested_dirs = None
- def setup_parser(self):
+ @staticmethod
+ def setup_parser(parser):
""" Initialise the option parser for 'gr_modtool info' """
- parser = ModTool.setup_parser(self)
- parser.usage = '%prog info [options]. \n Call %prog without any options to run it interactively.'
- ogroup = OptionGroup(parser, "Info options")
- ogroup.add_option("--python-readable", action="store_true", default=None,
- help="Return the output in a format that's easier to read for Python scripts.")
- ogroup.add_option("--suggested-dirs", default=None, type="string",
- help="Suggest typical include dirs if nothing better can be detected.")
- parser.add_option_group(ogroup)
+ #args_group = parser.add_argument_group(title="Info options")
+ parser.add_argument("--python-readable", action="store_true",
+ help="Return the output in a format that's easier to read for Python scripts.")
+ parser.add_argument("--suggested-dirs",
+ help="Suggest typical include dirs if nothing better can be detected.")
return parser
- def setup(self, options, args):
+ def setup(self, options):
# Won't call parent's setup(), because that's too chatty
self._directory = options.directory
self._python_readable = options.python_readable
self._suggested_dirs = options.suggested_dirs
- def run(self):
+ def run(self, options):
""" Go, go, go! """
+ self.setup(options)
mod_info = dict()
mod_info['base_dir'] = self._get_base_dir(self._directory)
if mod_info['base_dir'] is None:
@@ -72,7 +73,7 @@ class ModToolInfo(ModTool):
):
self._info['version'] = '37'
mod_info['version'] = self._info['version']
- if 'is_component' in self._info.keys() and self._info['is_component']:
+ if 'is_component' in list(self._info.keys()) and self._info['is_component']:
mod_info['is_component'] = True
mod_info['incdirs'] = []
mod_incl_dir = os.path.join(mod_info['base_dir'], 'include')
@@ -85,7 +86,7 @@ class ModToolInfo(ModTool):
mod_info['build_dir'] = build_dir
mod_info['incdirs'] += self._get_include_dirs(mod_info)
if self._python_readable:
- print str(mod_info)
+ print(str(mod_info))
else:
self._pretty_print(mod_info)
@@ -108,7 +109,7 @@ class ModToolInfo(ModTool):
If that hasn't happened, the build dir cannot be detected, unless it's
called 'build', which is then assumed to be the build dir. """
base_build_dir = mod_info['base_dir']
- if 'is_component' in mod_info.keys():
+ if 'is_component' in list(mod_info.keys()):
(base_build_dir, rest_dir) = os.path.split(base_build_dir)
has_build_dir = os.path.isdir(os.path.join(base_build_dir, 'build'))
if (has_build_dir and os.path.isfile(os.path.join(base_build_dir, 'CMakeCache.txt'))):
@@ -125,7 +126,7 @@ class ModToolInfo(ModTool):
""" Figure out include dirs for the make process. """
inc_dirs = []
path_or_internal = {True: 'INTERNAL',
- False: 'PATH'}['is_component' in mod_info.keys()]
+ False: 'PATH'}['is_component' in list(mod_info.keys())]
try:
cmakecache_fid = open(os.path.join(mod_info['build_dir'], 'CMakeCache.txt'))
for line in cmakecache_fid:
@@ -138,19 +139,19 @@ class ModToolInfo(ModTool):
inc_dirs = [os.path.normpath(path) for path in self._suggested_dirs.split(':') if os.path.isdir(path)]
return inc_dirs
- def _pretty_print(self, mod_info):
+ def _pretty_print(elf, mod_info):
""" Output the module info in human-readable format """
index_names = {'base_dir': 'Base directory',
'modname': 'Module name',
'is_component': 'Is GR component',
'build_dir': 'Build directory',
'incdirs': 'Include directories'}
- for key in mod_info.keys():
+ for key in list(mod_info.keys()):
if key == 'version':
- print " API version: %s" % {
- '36': 'pre-3.7',
- '37': 'post-3.7',
- 'autofoo': 'Autotools (pre-3.5)'
- }[mod_info['version']]
+ print(" API version: %s" % {
+ '36': 'pre-3.7',
+ '37': 'post-3.7',
+ 'autofoo': 'Autotools (pre-3.5)'
+ }[mod_info['version']])
else:
- print '%19s: %s' % (index_names[key], mod_info[key])
+ print('%19s: %s' % (index_names[key], mod_info[key]))
diff --git a/gr-utils/python/modtool/modtool_makexml.py b/gr-utils/python/modtool/modtool_makexml.py
index c45759c605..90308d1b14 100644
--- a/gr-utils/python/modtool/modtool_makexml.py
+++ b/gr-utils/python/modtool/modtool_makexml.py
@@ -20,49 +20,52 @@
#
""" Automatically create XML bindings for GRC from block code """
+from __future__ import print_function
+from __future__ import absolute_import
+from __future__ import unicode_literals
+
import os
import re
import glob
-from modtool_base import ModTool, ModToolException
-from parser_cc_block import ParserCCBlock
-from grc_xml_generator import GRCXMLGenerator
-from cmakefile_editor import CMakeFileEditor
-from util_functions import ask_yes_no
+from .modtool_base import ModTool, ModToolException
+from .parser_cc_block import ParserCCBlock
+from .grc_xml_generator import GRCXMLGenerator
+from .cmakefile_editor import CMakeFileEditor
+from .util_functions import ask_yes_no
class ModToolMakeXML(ModTool):
""" Make XML file for GRC block bindings """
name = 'makexml'
- aliases = ('mx',)
+ description = 'Generate XML files for GRC block bindings.'
def __init__(self):
ModTool.__init__(self)
- def setup_parser(self):
+ @staticmethod
+ def setup_parser(parser):
""" Initialise the option parser for 'gr_modtool makexml' """
- parser = ModTool.setup_parser(self)
- parser.usage = """%prog info [options]. \n Call %prog without any options to run it interactively.
+ parser.usage = """%s
Note: This does not work on Python blocks!
- """
- return parser
+ """ % parser.usage
+ ModTool.setup_parser_block(parser)
- def setup(self, options, args):
- ModTool.setup(self, options, args)
+ def setup(self, options):
+ ModTool.setup(self, options)
- if options.block_name is not None:
- self._info['pattern'] = options.block_name
- elif len(args) >= 2:
- self._info['pattern'] = args[1]
+ if options.blockname is not None:
+ self._info['pattern'] = options.blockname
else:
- self._info['pattern'] = raw_input('Which blocks do you want to parse? (Regex): ')
- if not self._info['pattern'] or self._info['pattern'].isspace():
+ self._info['pattern'] = input('Which blocks do you want to parse? (Regex): ')
+ if len(self._info['pattern']) == 0:
self._info['pattern'] = '.'
- def run(self):
+ def run(self, options):
""" Go, go, go! """
- print "Warning: This is an experimental feature. Don't expect any magic."
+ print("Warning: This is an experimental feature. Don't expect any magic.")
+ self.setup(options)
# 1) Go through lib/
if not self._skip_subdirs['lib']:
if self._info['version'] == '37':
@@ -81,12 +84,12 @@ class ModToolMakeXML(ModTool):
""" Search for files matching pattern in the given path. """
files = sorted(glob.glob("%s/%s"% (path, path_glob)))
files_filt = []
- print "Searching for matching files in %s/:" % path
+ print("Searching for matching files in %s/:" % path)
for f in files:
if re.search(self._info['pattern'], os.path.basename(f)) is not None:
files_filt.append(f)
- if not files_filt:
- print "None found."
+ if len(files_filt) == 0:
+ print("None found.")
return files_filt
def _make_grc_xml_from_block_data(self, params, iosig, blockname):
@@ -111,7 +114,7 @@ class ModToolMakeXML(ModTool):
return
else:
file_exists = True
- print "Warning: Overwriting existing GRC file."
+ print("Warning: Overwriting existing GRC file.")
grc_generator = GRCXMLGenerator(
modname=self._info['modname'],
blockname=blockname,
@@ -126,7 +129,7 @@ class ModToolMakeXML(ModTool):
if not self._skip_subdirs['grc']:
ed = CMakeFileEditor(self._file['cmgrc'])
if re.search(fname_xml, ed.cfile) is None and not ed.check_for_glob('*.xml'):
- print "Adding GRC bindings to grc/CMakeLists.txt..."
+ print("Adding GRC bindings to grc/CMakeLists.txt...")
ed.append_value('install', fname_xml, to_ignore_end='DESTINATION[^()]+')
ed.write()
self.scm.mark_files_updated(self._file['cmgrc'])
@@ -159,7 +162,7 @@ class ModToolMakeXML(ModTool):
blockname = blockname.replace(self._info['modname']+'_', '', 1)
return (blockname, fname_h)
# Go, go, go
- print "Making GRC bindings for %s..." % fname_cc
+ print("Making GRC bindings for %s..." % fname_cc)
(blockname, fname_h) = _get_blockdata(fname_cc)
try:
parser = ParserCCBlock(fname_cc,
diff --git a/gr-utils/python/modtool/modtool_newmod.py b/gr-utils/python/modtool/modtool_newmod.py
index 43ea44618e..c283204ee2 100644
--- a/gr-utils/python/modtool/modtool_newmod.py
+++ b/gr-utils/python/modtool/modtool_newmod.py
@@ -20,38 +20,40 @@
#
""" Create a whole new out-of-tree module """
+from __future__ import print_function
+from __future__ import absolute_import
+from __future__ import unicode_literals
+
import shutil
import os
import re
-from optparse import OptionGroup
from gnuradio import gr
-from modtool_base import ModTool, ModToolException
+from .modtool_base import ModTool, ModToolException
+from .scm import SCMRepoFactory
class ModToolNewModule(ModTool):
""" Create a new out-of-tree module """
name = 'newmod'
- aliases = ('nm', 'create')
+ description = 'Create new empty module, use add to add blocks.'
def __init__(self):
ModTool.__init__(self)
- def setup_parser(self):
+ @staticmethod
+ def setup_parser(parser):
" Initialise the option parser for 'gr_modtool newmod' "
- parser = ModTool.setup_parser(self)
- parser.usage = '%prog nm [options]. \n Call %prog without any options to run it interactively.'
- ogroup = OptionGroup(parser, "New out-of-tree module options")
- ogroup.add_option("--srcdir", type="string",
- help="Source directory for the module template.")
- parser.add_option_group(ogroup)
- return parser
+ parser.add_argument("--srcdir",
+ help="Source directory for the module template.")
+ parser.add_argument("module_name", metavar='MODULE-NAME', nargs='?',
+ help="Override the current module's name (normally is autodetected).")
- def setup(self, options, args):
+ def setup(self, options):
# Don't call ModTool.setup(), that assumes an existing module.
self._info['modname'] = options.module_name
if self._info['modname'] is None:
- if len(args) >= 2:
- self._info['modname'] = args[1]
+ if options.module_name:
+ self._info['modname'] = options.module_name
else:
- self._info['modname'] = raw_input('Name of the new module: ')
+ self._info['modname'] = input('Name of the new module: ')
if not re.match('[a-zA-Z0-9_]+$', self._info['modname']):
raise ModToolException('Invalid module name.')
self._dir = options.directory
@@ -71,13 +73,14 @@ class ModToolNewModule(ModTool):
self.options = options
self._setup_scm(mode='new')
- def run(self):
+ def run(self, options):
"""
* Copy the example dir recursively
* Open all files, rename howto and HOWTO to the module name
* Rename files and directories that contain the word howto
"""
- print "Creating out-of-tree module in %s..." % self._dir,
+ self.setup(options)
+ print("Creating out-of-tree module in %s..." % (self._dir,))
try:
shutil.copytree(self._srcdir, self._dir)
os.chdir(self._dir)
@@ -94,7 +97,8 @@ class ModToolNewModule(ModTool):
os.rename(f, os.path.join(root, filename.replace('howto', self._info['modname'])))
if os.path.basename(root) == 'howto':
os.rename(root, os.path.join(os.path.dirname(root), self._info['modname']))
- print "Done."
+ print("Done.")
if self.scm.init_repo(path_to_repo="."):
- print "Created repository... you might want to commit before continuing."
- print "Use 'gr_modtool add' to add a new block to this currently empty module."
+ print("Created repository... you might want to commit before continuing.")
+ print("Use 'gr_modtool add' to add a new block to this currently empty module.")
+
diff --git a/gr-utils/python/modtool/modtool_rename.py b/gr-utils/python/modtool/modtool_rename.py
index dd9b0eaee8..4af860b5d4 100644
--- a/gr-utils/python/modtool/modtool_rename.py
+++ b/gr-utils/python/modtool/modtool_rename.py
@@ -20,16 +20,22 @@
#
""" Module to rename blocks """
+from __future__ import print_function
+from __future__ import absolute_import
+from __future__ import unicode_literals
+
import os
import re
-from optparse import OptionGroup
-from modtool_base import ModTool, ModToolException
+from .util_functions import append_re_line_sequence, ask_yes_no
+from .cmakefile_editor import CMakeFileEditor
+from .modtool_base import ModTool, ModToolException
+from .templates import Templates
class ModToolRename(ModTool):
""" Rename a block in the out-of-tree module. """
name = 'rename'
- aliases = ('mv',)
+ description = 'Rename block inside module.'
def __init__(self):
ModTool.__init__(self)
@@ -38,53 +44,47 @@ class ModToolRename(ModTool):
self._skip_cmakefiles = False
self._license_file = None
- def setup_parser(self):
- parser = ModTool.setup_parser(self)
- ogroup = OptionGroup(parser, "Rename module options")
- ogroup.add_option("-o", "--old-name", type="string", default=None,
- help="Current name of the block to rename.")
- ogroup.add_option("-u", "--new-name", type="string", default=None,
- help="New name of the block.")
- parser.add_option_group(ogroup)
+ @staticmethod
+ def setup_parser(parser):
+ #parser = parser.add_argument_group(title="Rename module options")
+ ModTool.setup_parser_block(parser)
+ parser.add_argument("new_name", nargs="?", metavar='NEW-BLOCK-NAME',
+ help="New name of the block.")
return parser
- def setup(self, options, args):
- ModTool.setup(self, options, args)
+ def setup(self, options):
+ ModTool.setup(self, options)
if ((self._skip_subdirs['lib'] and self._info['lang'] == 'cpp')
or (self._skip_subdirs['python'] and self._info['lang'] == 'python')):
raise ModToolException('Missing or skipping relevant subdir.')
# first make sure the old block name is provided
- self._info['oldname'] = options.old_name
+ self._info['oldname'] = options.blockname
if self._info['oldname'] is None:
- if len(args) >= 2:
- self._info['oldname'] = args[1]
- else:
- self._info['oldname'] = raw_input("Enter name of block/code to rename (without module name prefix): ")
+ self._info['oldname'] = input("Enter name of block/code to rename (without module name prefix): ")
if not re.match('[a-zA-Z0-9_]+', self._info['oldname']):
raise ModToolException('Invalid block name.')
- print "Block/code to rename identifier: " + self._info['oldname']
+ print("Block/code to rename identifier: " + self._info['oldname'])
self._info['fulloldname'] = self._info['modname'] + '_' + self._info['oldname']
# now get the new block name
- self._info['newname'] = options.new_name
- if self._info['newname'] is None:
- if len(args) >= 2:
- self._info['newname'] = args[2]
- else:
- self._info['newname'] = raw_input("Enter name of block/code (without module name prefix): ")
+ if options.new_name is None:
+ self._info['newname'] = input("Enter name of block/code (without module name prefix): ")
+ else:
+ self._info['newname'] = options.new_name[0]
if not re.match('[a-zA-Z0-9_]+', self._info['newname']):
raise ModToolException('Invalid block name.')
- print "Block/code identifier: " + self._info['newname']
+ print("Block/code identifier: " + self._info['newname'])
self._info['fullnewname'] = self._info['modname'] + '_' + self._info['newname']
- def run(self):
+ def run(self, options):
""" Go, go, go. """
+ self.setup(options)
module = self._info['modname']
oldname = self._info['oldname']
newname = self._info['newname']
- print "In module '%s' rename block '%s' to '%s'" % (module, oldname, newname)
+ print("In module '%s' rename block '%s' to '%s'" % (module, oldname, newname))
self._run_swig_rename(self._file['swig'], oldname, newname)
self._run_grc_rename(self._info['modname'], oldname, newname)
self._run_python_qa(self._info['modname'], oldname, newname)
@@ -97,11 +97,11 @@ class ModToolRename(ModTool):
""" Rename SWIG includes and block_magic """
nsubs = self._run_file_replace(swigfilename, old, new)
if nsubs < 1:
- print "Couldn't find '%s' in file '%s'." % (old, swigfilename)
+ print("Couldn't find '%s' in file '%s'." % (old, swigfilename))
if nsubs == 2:
- print "Changing 'noblock' type file"
+ print("Changing 'noblock' type file")
if nsubs > 3:
- print "Hm, changed more then expected while editing %s." % swigfilename
+ print("Hm, changed more then expected while editing %s." % swigfilename)
return False
def _run_lib(self, module, old, new):
@@ -121,7 +121,7 @@ class ModToolRename(ModTool):
filename = 'qa_' + module + '.cc'
nsubs = self._run_file_replace(path + filename, old, new)
if nsubs > 0:
- print "C++ QA code detected, renaming..."
+ print("C++ QA code detected, renaming...")
filename = 'qa_' + old + '.cc'
self._run_file_replace(path + filename, old, new)
filename = 'qa_' + old + '.h'
@@ -129,7 +129,7 @@ class ModToolRename(ModTool):
self._run_file_replace(path + filename, old.upper(), new.upper())
self._run_file_rename(path, 'qa_' + old, 'qa_' + new)
else:
- print "No C++ QA code detected, skipping..."
+ print("No C++ QA code detected, skipping...")
def _run_include(self, module, old, new):
path = './include/' + module + '/'
@@ -144,13 +144,13 @@ class ModToolRename(ModTool):
filename = '__init__.py'
nsubs = self._run_file_replace(path + filename, old, new)
if nsubs > 0:
- print "Python block detected, renaming..."
+ print("Python block detected, renaming...")
filename = old + '.py'
self._run_file_replace(path + filename, old, new)
self._run_cmakelists(path, old, new)
self._run_file_rename(path, old, new)
else:
- print "Not a Python block, nothing to do here..."
+ print("Not a Python block, nothing to do here...")
def _run_python_qa(self, module, old, new):
new = 'qa_' + new
@@ -170,7 +170,7 @@ class ModToolRename(ModTool):
filename = path + 'CMakeLists.txt'
nsubs = self._run_file_replace(filename, first, second)
if nsubs < 1:
- print "'%s' wasn't in '%s'." % (first, filename)
+ print("'%s' wasn't in '%s'." % (first, filename))
def _run_file_rename(self, path, old, new):
files = os.listdir(path)
@@ -179,14 +179,14 @@ class ModToolRename(ModTool):
nl = file.replace(old, new)
src = path + file
dst = path + nl
- print "Renaming file '%s' to '%s'." % (src, dst)
+ print("Renaming file '%s' to '%s'." % (src, dst))
os.rename(src, dst)
def _run_file_replace(self, filename, old, new):
if not os.path.isfile(filename):
return False
else:
- print "In '%s' renaming occurrences of '%s' to '%s'" % (filename, old, new)
+ print("In '%s' renaming occurrences of '%s' to '%s'" % (filename, old, new))
cfile = open(filename).read()
(cfile, nsubs) = re.subn(old, new, cfile)
diff --git a/gr-utils/python/modtool/modtool_rm.py b/gr-utils/python/modtool/modtool_rm.py
index 79d8344a72..7395c99bea 100644
--- a/gr-utils/python/modtool/modtool_rm.py
+++ b/gr-utils/python/modtool/modtool_rm.py
@@ -20,50 +20,45 @@
#
""" Remove blocks module """
+from __future__ import print_function
+from __future__ import absolute_import
+from __future__ import unicode_literals
+
import os
import re
import sys
import glob
-from util_functions import remove_pattern_from_file, SequenceCompleter
-from modtool_base import ModTool
-from cmakefile_editor import CMakeFileEditor
+from .util_functions import remove_pattern_from_file, SequenceCompleter
+from .modtool_base import ModTool
+from .cmakefile_editor import CMakeFileEditor
class ModToolRemove(ModTool):
""" Remove block (delete files and remove Makefile entries) """
name = 'remove'
- aliases = ('rm', 'del')
+ description = 'Remove block from module.'
def __init__(self):
ModTool.__init__(self)
- def get_block_candidates(self):
- cpp_blocks = filter(lambda x: not (x.startswith('qa_') or
- x.startswith('test_')),
- glob.glob1("lib", "*.cc"))
- python_blocks = filter(lambda x: not (x.startswith('qa_') or
- x.startswith('build') or
- x.startswith('__init__')),
- glob.glob1("python", "*.py"))
- block_candidates = [x.split('_impl')[0] for x in cpp_blocks] + [x.split('.')[0] for x in python_blocks]
- return block_candidates
+ @staticmethod
+ def setup_parser(parser):
+ ModTool.setup_parser_block(parser)
- def setup(self, options, args):
- ModTool.setup(self, options, args)
+ def setup(self, options):
+ ModTool.setup(self, options)
- if options.block_name is not None:
- self._info['pattern'] = options.block_name
- elif len(args) >= 2:
- self._info['pattern'] = args[1]
+ if options.blockname is not None:
+ self._info['pattern'] = options.blockname
else:
block_candidates = self.get_block_candidates()
with SequenceCompleter(block_candidates):
- self._info['pattern'] = raw_input('Which blocks do you want to delete? (Regex): ')
+ self._info['pattern'] = input('Which blocks do you want to delete? (Regex): ')
if not self._info['pattern'] or self._info['pattern'].isspace():
self._info['pattern'] = '.'
- def run(self):
+ def run(self, options):
""" Go, go, go! """
def _remove_cc_test_case(filename=None, ed=None):
""" Special function that removes the occurrences of a qa*.cc file
@@ -109,6 +104,7 @@ class ModToolRemove(ModTool):
(self._info['modname'], pyblockname, self._info['modname'], filename)
return regexp
# Go, go, go!
+ self.setup(options)
if not self._skip_subdirs['lib']:
self._run_subdir('lib', ('*.cc', '*.h'), ('add_library', 'list'),
cmakeedit_func=_remove_cc_test_case)
@@ -142,12 +138,12 @@ class ModToolRemove(ModTool):
for g in globs:
files = files + sorted(glob.glob("%s/%s"% (path, g)))
files_filt = []
- print "Searching for matching files in %s/:" % path
+ print("Searching for matching files in %s/:" % path)
for f in files:
if re.search(self._info['pattern'], os.path.basename(f)) is not None:
files_filt.append(f)
- if not files_filt:
- print "None found."
+ if len(files_filt) == 0:
+ print("None found.")
return []
# 2. Delete files, Makefile entries and other occurrences
files_deleted = []
@@ -156,7 +152,7 @@ class ModToolRemove(ModTool):
for f in files_filt:
b = os.path.basename(f)
if not yes:
- ans = raw_input("Really delete %s? [Y/n/a/q]: " % f).lower().strip()
+ ans = input("Really delete %s? [Y/n/a/q]: " % f).lower().strip()
if ans == 'a':
yes = True
if ans == 'q':
@@ -164,10 +160,10 @@ class ModToolRemove(ModTool):
if ans == 'n':
continue
files_deleted.append(b)
- print "Deleting %s." % f
+ print("Deleting %s." % f)
self.scm.remove_file(f)
os.unlink(f)
- print "Deleting occurrences of %s from %s/CMakeLists.txt..." % (b, path)
+ print("Deleting occurrences of %s from %s/CMakeLists.txt..." % (b, path))
for var in makefile_vars:
ed.remove_value(var, b)
if cmakeedit_func is not None:
diff --git a/gr-utils/python/modtool/parser_cc_block.py b/gr-utils/python/modtool/parser_cc_block.py
index 703522c8fb..fffdf309d8 100644
--- a/gr-utils/python/modtool/parser_cc_block.py
+++ b/gr-utils/python/modtool/parser_cc_block.py
@@ -19,6 +19,10 @@
# Boston, MA 02110-1301, USA.
#
''' A parser for blocks written in C++ '''
+
+from __future__ import print_function
+from __future__ import unicode_literals
+
import re
import sys
@@ -42,7 +46,7 @@ class ParserCCBlock(object):
E.g., for sizeof(int), it will return 'int'.
Returns a list! """
if 'gr::io_signature::makev' in iosigcall:
- print 'tbi'
+ print('tbi')
raise ValueError
return {'type': [_typestr_to_iotype(x) for x in typestr.split(',')],
'vlen': [_typestr_to_vlen(x) for x in typestr.split(',')]
@@ -82,15 +86,15 @@ class ParserCCBlock(object):
iosig_match.group('intype'))
iosig['in']['min_ports'] = iosig_match.group('inmin')
iosig['in']['max_ports'] = iosig_match.group('inmax')
- except ValueError, Exception:
- print "Error: Can't parse input signature."
+ except Exception:
+ print("Error: Can't parse input signature.")
try:
iosig['out'] = _figure_out_iotype_and_vlen(iosig_match.group('outcall'),
iosig_match.group('outtype'))
iosig['out']['min_ports'] = iosig_match.group('outmin')
iosig['out']['max_ports'] = iosig_match.group('outmax')
- except ValueError, Exception:
- print "Error: Can't parse output signature."
+ except Exception:
+ print("Error: Can't parse output signature.")
return iosig
@@ -213,7 +217,7 @@ class ParserCCBlock(object):
try:
params_list = _scan_param_list(make_match.end(0))
except ValueError as ve:
- print "Can't parse the argument list: ", ve.args[0]
+ print("Can't parse the argument list: ", ve.args[0])
sys.exit(0)
params = []
for plist in params_list:
diff --git a/gr-utils/python/modtool/scm.py b/gr-utils/python/modtool/scm.py
index aa4f94d531..4b3d5116ac 100644
--- a/gr-utils/python/modtool/scm.py
+++ b/gr-utils/python/modtool/scm.py
@@ -20,6 +20,9 @@
#
""" Class to handle source code management repositories. """
+from __future__ import print_function
+from __future__ import unicode_literals
+
import subprocess
try:
@@ -198,12 +201,12 @@ class SCMRepoFactory(object):
""" Returns a valid, usable object of type SCMRepository. """
if self.options.scm_mode == 'no':
return SCMRepository(self.path_to_repo)
- for glbl in globals().values():
+ for glbl in list(globals().values()):
try:
if issubclass(glbl, SCMRepository):
the_scm = glbl(self.path_to_repo)
if the_scm.is_active():
- print 'Found SCM of type:', the_scm.handles_scm_type
+ print('Found SCM of type:', the_scm.handles_scm_type)
return the_scm
except (TypeError, AttributeError, InvalidSCMError):
pass
@@ -215,7 +218,7 @@ class SCMRepoFactory(object):
""" Returns a valid, usable object of type SCMRepository for an uninitialized dir. """
if self.options.scm_mode == 'no':
return SCMRepository(self.path_to_repo)
- for glbl in globals().values():
+ for glbl in list(globals().values()):
try:
if issubclass(glbl, SCMRepository):
if glbl.handles_scm_type == scm_type:
diff --git a/gr-utils/python/modtool/templates.py b/gr-utils/python/modtool/templates.py
index 6586830d82..10ee4a4e6c 100644
--- a/gr-utils/python/modtool/templates.py
+++ b/gr-utils/python/modtool/templates.py
@@ -1,5 +1,5 @@
#
-# Copyright 2013 Free Software Foundation, Inc.
+# Copyright 2013-2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
@@ -19,6 +19,7 @@
# Boston, MA 02110-1301, USA.
#
''' All the templates for skeleton files (needed by ModToolAdd) '''
+from __future__ import unicode_literals
from datetime import datetime
@@ -45,7 +46,7 @@ Boston, MA 02110-1301, USA.
''' % datetime.now().year
Templates['grlicense'] = '''
-Copyright %d Free Software Foundation, Inc.
+Copyright {0} Free Software Foundation, Inc.
This file is part of GNU Radio
@@ -63,15 +64,15 @@ You should have received a copy of the GNU General Public License
along with GNU Radio; see the file COPYING. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street,
Boston, MA 02110-1301, USA.
-''' % datetime.now().year
+'''.format(datetime.now().year)
# Header file of a sync/decimator/interpolator block
Templates['block_impl_h'] = '''/* -*- c++ -*- */
-${str_to_fancyc_comment($license)}
-\#ifndef INCLUDED_${modname.upper()}_${blockname.upper()}_IMPL_H
-\#define INCLUDED_${modname.upper()}_${blockname.upper()}_IMPL_H
+${str_to_fancyc_comment(license)}
+#ifndef INCLUDED_${modname.upper()}_${blockname.upper()}_IMPL_H
+#define INCLUDED_${modname.upper()}_${blockname.upper()}_IMPL_H
-\#include <${include_dir_prefix}/${blockname}.h>
+#include <${include_dir_prefix}/${blockname}.h>
namespace gr {
namespace ${modname} {
@@ -81,112 +82,118 @@ namespace gr {
private:
// Nothing to declare in this block.
-#if $blocktype == 'tagged_stream'
+% if blocktype == 'tagged_stream':
protected:
int calculate_output_stream_length(const gr_vector_int &ninput_items);
-#end if
+% endif
public:
- ${blockname}_impl(${strip_default_values($arglist)});
+ ${blockname}_impl(${strip_default_values(arglist)});
~${blockname}_impl();
// Where all the action really happens
-#if $blocktype == 'general'
+% if blocktype == 'general':
void forecast (int noutput_items, gr_vector_int &ninput_items_required);
int general_work(int noutput_items,
gr_vector_int &ninput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items);
-#else if $blocktype == 'tagged_stream'
- int work(int noutput_items,
- gr_vector_int &ninput_items,
- gr_vector_const_void_star &input_items,
- gr_vector_void_star &output_items);
-#else if $blocktype == 'hier'
-#silent pass
-#else
- int work(int noutput_items,
- gr_vector_const_void_star &input_items,
- gr_vector_void_star &output_items);
-#end if
+
+% elif blocktype == 'tagged_stream':
+ int work(
+ int noutput_items,
+ gr_vector_int &ninput_items,
+ gr_vector_const_void_star &input_items,
+ gr_vector_void_star &output_items
+ );
+% elif blocktype == 'hier':
+% else:
+ int work(
+ int noutput_items,
+ gr_vector_const_void_star &input_items,
+ gr_vector_void_star &output_items
+ );
+% endif
};
} // namespace ${modname}
} // namespace gr
-\#endif /* INCLUDED_${modname.upper()}_${blockname.upper()}_IMPL_H */
+#endif /* INCLUDED_${modname.upper()}_${blockname.upper()}_IMPL_H */
'''
# C++ file of a GR block
Templates['block_impl_cpp'] = '''/* -*- c++ -*- */
-${str_to_fancyc_comment($license)}
-\#ifdef HAVE_CONFIG_H
-\#include "config.h"
-\#endif
-
-\#include <gnuradio/io_signature.h>
-#if $blocktype == 'noblock'
-\#include <${include_dir_prefix}/${blockname}.h>
-#else
-\#include "${blockname}_impl.h"
-#end if
+${str_to_fancyc_comment(license)}
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include <gnuradio/io_signature.h>
+% if blocktype == 'noblock':
+#include <${include_dir_prefix}/${blockname}.h>
+% else:
+#include "${blockname}_impl.h"
+% endif
namespace gr {
namespace ${modname} {
-#if $blocktype == 'noblock'
- $blockname::${blockname}(${strip_default_values($arglist)})
+% if blocktype == 'noblock':
+ ${blockname}::${blockname}(${strip_default_values(arglist)})
{
}
- $blockname::~${blockname}()
+ ${blockname}::~${blockname}()
{
}
-#else
+% else:
${blockname}::sptr
- ${blockname}::make(${strip_default_values($arglist)})
+ ${blockname}::make(${strip_default_values(arglist)})
{
return gnuradio::get_initial_sptr
- (new ${blockname}_impl(${strip_arg_types($arglist)}));
+ (new ${blockname}_impl(${strip_arg_types(arglist)}));
}
-#if $blocktype == 'decimator'
-#set $decimation = ', <+decimation+>'
-#else if $blocktype == 'interpolator'
-#set $decimation = ', <+interpolation+>'
-#else if $blocktype == 'tagged_stream'
-#set $decimation = ', <+len_tag_key+>'
-#else
-#set $decimation = ''
-#end if
-#if $blocktype == 'source'
-#set $inputsig = '0, 0, 0'
-#else
-#set $inputsig = '<+MIN_IN+>, <+MAX_IN+>, sizeof(<+ITYPE+>)'
-#end if
-#if $blocktype == 'sink'
-#set $outputsig = '0, 0, 0'
-#else
-#set $outputsig = '<+MIN_OUT+>, <+MAX_OUT+>, sizeof(<+OTYPE+>)'
-#end if
+<%
+ if blocktype == 'decimator':
+ decimation = ', <+decimation+>'
+ elif blocktype == 'interpolator':
+ decimation = ', <+interpolation+>'
+ elif blocktype == 'tagged_stream':
+ decimation = ', <+len_tag_key+>'
+ else:
+ decimation = ''
+ endif
+ if blocktype == 'source':
+ inputsig = '0, 0, 0'
+ else:
+ inputsig = '<+MIN_IN+>, <+MAX_IN+>, sizeof(<+ITYPE+>)'
+ endif
+ if blocktype == 'sink':
+ outputsig = '0, 0, 0'
+ else:
+ outputsig = '<+MIN_OUT+>, <+MAX_OUT+>, sizeof(<+OTYPE+>)'
+ endif
+%>
/*
* The private constructor
*/
- ${blockname}_impl::${blockname}_impl(${strip_default_values($arglist)})
+ ${blockname}_impl::${blockname}_impl(${strip_default_values(arglist)})
: gr::${grblocktype}("${blockname}",
- gr::io_signature::make($inputsig),
- gr::io_signature::make($outputsig)$decimation)
-#if $blocktype == 'hier'
+ gr::io_signature::make(${inputsig}),
+ gr::io_signature::make(${outputsig})${decimation})
+ % if blocktype == 'hier':
{
connect(self(), 0, d_firstblock, 0);
// connect other blocks
connect(d_lastblock, 0, self(), 0);
}
-#else
+ % else:
{}
-#end if
+ % endif
/*
* Our virtual destructor.
@@ -195,7 +202,7 @@ namespace gr {
{
}
-#if $blocktype == 'general'
+ % if blocktype == 'general':
void
${blockname}_impl::forecast (int noutput_items, gr_vector_int &ninput_items_required)
{
@@ -219,7 +226,7 @@ namespace gr {
// Tell runtime system how many output items we produced.
return noutput_items;
}
-#else if $blocktype == 'tagged_stream'
+ % elif blocktype == 'tagged_stream':
int
${blockname}_impl::calculate_output_stream_length(const gr_vector_int &ninput_items)
{
@@ -241,32 +248,27 @@ namespace gr {
// Tell runtime system how many output items we produced.
return noutput_items;
}
-#else if $blocktype == 'hier'
-#silent pass
-#else
+ % elif blocktype == 'hier':
+ % else:
int
${blockname}_impl::work(int noutput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items)
{
-#if $blocktype == 'source'
-#silent pass
-#else
+ % if blocktype != 'source':
const <+ITYPE+> *in = (const <+ITYPE+> *) input_items[0];
-#end if
-#if $blocktype == 'sink'
-#silent pass
-#else
+ % endif
+ % if blocktype != 'sink':
<+OTYPE+> *out = (<+OTYPE+> *) output_items[0];
-#end if
+ % endif
// Do <+signal processing+>
// Tell runtime system how many output items we produced.
return noutput_items;
}
-#end if
-#end if
+ % endif
+% endif
} /* namespace ${modname} */
} /* namespace gr */
@@ -275,38 +277,38 @@ namespace gr {
# Block definition header file (for include/)
Templates['block_def_h'] = '''/* -*- c++ -*- */
-${str_to_fancyc_comment($license)}
+${str_to_fancyc_comment(license)}
-\#ifndef INCLUDED_${modname.upper()}_${blockname.upper()}_H
-\#define INCLUDED_${modname.upper()}_${blockname.upper()}_H
+#ifndef INCLUDED_${modname.upper()}_${blockname.upper()}_H
+#define INCLUDED_${modname.upper()}_${blockname.upper()}_H
-\#include <${include_dir_prefix}/api.h>
-#if $blocktype != 'noblock'
-\#include <gnuradio/${grblocktype}.h>
-#end if
+#include <${include_dir_prefix}/api.h>
+% if blocktype != 'noblock':
+#include <gnuradio/${grblocktype}.h>
+% endif
namespace gr {
namespace ${modname} {
-#if $blocktype == 'noblock'
+% if blocktype == 'noblock':
/*!
* \\brief <+description+>
*
*/
- class ${modname.upper()}_API $blockname
+ class ${modname.upper()}_API ${blockname}
{
public:
${blockname}(${arglist});
~${blockname}();
private:
};
-#else
+% else:
/*!
* \\brief <+description of block+>
* \ingroup ${modname}
*
*/
- class ${modname.upper()}_API ${blockname} : virtual public gr::$grblocktype
+ class ${modname.upper()}_API ${blockname} : virtual public gr::${grblocktype}
{
public:
typedef boost::shared_ptr<${blockname}> sptr;
@@ -319,85 +321,94 @@ namespace gr {
* class. ${modname}::${blockname}::make is the public interface for
* creating new instances.
*/
- static sptr make($arglist);
+ static sptr make(${arglist});
};
-#end if
+% endif
} // namespace ${modname}
} // namespace gr
-\#endif /* INCLUDED_${modname.upper()}_${blockname.upper()}_H */
+#endif /* INCLUDED_${modname.upper()}_${blockname.upper()}_H */
'''
# Python block
-Templates['block_python'] = '''\#!/usr/bin/env python
+Templates['block_python'] = '''#!/usr/bin/env python
# -*- coding: utf-8 -*-
-${str_to_python_comment($license)}
-#
-#if $blocktype == 'noblock'
-#stop
-#end if
-
-#if $blocktype in ('sync', 'sink', 'source')
-#set $parenttype = 'gr.sync_block'
-#else
-#set $parenttype = {'hier': 'gr.hier_block2', 'interpolator': 'gr.interp_block', 'decimator': 'gr.decim_block', 'general': 'gr.basic_block'}[$blocktype]
-#end if
-#if $blocktype != 'hier'
-import numpy
-#if $blocktype == 'source'
-#set $inputsig = 'None'
-#else
-#set $inputsig = '[<+numpy.float32+>]'
-#end if
-#if $blocktype == 'sink'
-#set $outputsig = 'None'
-#else
-#set $outputsig = '[<+numpy.float32+>]'
-#end if
-#else
-#if $blocktype == 'source'
-#set $inputsig = '0, 0, 0'
-#else
-#set $inputsig = '<+MIN_IN+>, <+MAX_IN+>, gr.sizeof_<+ITYPE+>'
-#end if
-#if $blocktype == 'sink'
-#set $outputsig = '0, 0, 0'
-#else
-#set $outputsig = '<+MIN_OUT+>, <+MAX_OUT+>, gr.sizeof_<+OTYPE+>'
-#end if
-#end if
-#if $blocktype == 'interpolator'
-#set $deciminterp = ', <+interpolation+>'
-#else if $blocktype == 'decimator'
-#set $deciminterp = ', <+decimation+>'
-#else
-#set $deciminterp = ''
-#end if
-from gnuradio import gr
+${str_to_python_comment(license)}
+#\
+<%
+ if blocktype == 'noblock':
+ return
+ if blocktype in ('sync', 'sink', 'source'):
+ parenttype = 'gr.sync_block'
+ else:
+ parenttype = {
+ 'hier': 'gr.hier_block2',
+ 'interpolator': 'gr.interp_block',
+ 'decimator': 'gr.decim_block',
+ 'general': 'gr.basic_block'
+ }[blocktype]
+%>
+% if blocktype != 'hier':
+
+import numpy\
+<%
+ if blocktype == 'source':
+ inputsig = 'None'
+ else:
+ inputsig = '[<+numpy.float32+>]'
+ if blocktype == 'sink':
+ outputsig = 'None'
+ else:
+ outputsig = '[<+numpy.float32+>]'
+%>
+% else:
+<%
+ if blocktype == 'source':
+ inputsig = '0, 0, 0'
+ else:
+ inputsig = '<+MIN_IN+>, <+MAX_IN+>, gr.sizeof_<+ITYPE+>'
+ if blocktype == 'sink':
+ outputsig = '0, 0, 0'
+ else:
+ outputsig = '<+MIN_OUT+>, <+MAX_OUT+>, gr.sizeof_<+OTYPE+>'
+%>
+% endif
+<%
+ if blocktype == 'interpolator':
+ deciminterp = ', <+interpolation+>'
+ elif blocktype == 'decimator':
+ deciminterp = ', <+decimation+>'
+ else:
+ deciminterp = ''
+ if arglist == '':
+ arglistsep = ''
+ else:
+ arglistsep = ', '
+%>from gnuradio import gr
class ${blockname}(${parenttype}):
"""
docstring for block ${blockname}
"""
- def __init__(self#if $arglist == '' then '' else ', '#$arglist):
+ def __init__(self${arglistsep}${arglist}):
${parenttype}.__init__(self,
-#if $blocktype == 'hier'
- "$blockname",
+% if blocktype == 'hier':
+ "${blockname}",
gr.io_signature(${inputsig}), # Input signature
gr.io_signature(${outputsig})) # Output signature
# Define blocks and connect them
self.connect()
-#stop
-#else
+<% return %>
+% else:
name="${blockname}",
in_sig=${inputsig},
out_sig=${outputsig}${deciminterp})
-#end if
+% endif
-#if $blocktype == 'general'
+% if blocktype == 'general':
def forecast(self, noutput_items, ninput_items_required):
#setup size of input_items[i] for work call
for i in range(len(ninput_items_required)):
@@ -408,37 +419,37 @@ class ${blockname}(${parenttype}):
consume(0, len(input_items[0]))
\#self.consume_each(len(input_items[0]))
return len(output_items[0])
-#stop
-#end if
+<% return %>
+% endif
def work(self, input_items, output_items):
-#if $blocktype != 'source'
+% if blocktype != 'source':
in0 = input_items[0]
-#end if
-#if $blocktype != 'sink'
+% endif
+% if blocktype != 'sink':
out = output_items[0]
-#end if
+% endif
# <+signal processing here+>
-#if $blocktype in ('sync', 'decimator', 'interpolator')
+% if blocktype in ('sync', 'decimator', 'interpolator'):
out[:] = in0
return len(output_items[0])
-#else if $blocktype == 'sink'
+% elif blocktype == 'sink':
return len(input_items[0])
-#else if $blocktype == 'source'
+% elif blocktype == 'source':
out[:] = whatever
return len(output_items[0])
-#end if
+% endif
'''
# C++ file for QA
Templates['qa_cpp'] = '''/* -*- c++ -*- */
-${str_to_fancyc_comment($license)}
+${str_to_fancyc_comment(license)}
-\#include <gnuradio/attributes.h>
-\#include <cppunit/TestAssert.h>
-\#include "qa_${blockname}.h"
-\#include <${include_dir_prefix}/${blockname}.h>
+#include <gnuradio/attributes.h>
+#include <cppunit/TestAssert.h>
+#include "qa_${blockname}.h"
+#include <${include_dir_prefix}/${blockname}.h>
namespace gr {
namespace ${modname} {
@@ -456,13 +467,13 @@ namespace gr {
# Header file for QA
Templates['qa_h'] = '''/* -*- c++ -*- */
-${str_to_fancyc_comment($license)}
+${str_to_fancyc_comment(license)}
-\#ifndef _QA_${blockname.upper()}_H_
-\#define _QA_${blockname.upper()}_H_
+#ifndef _QA_${blockname.upper()}_H_
+#define _QA_${blockname.upper()}_H_
-\#include <cppunit/extensions/HelperMacros.h>
-\#include <cppunit/TestCase.h>
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/TestCase.h>
namespace gr {
namespace ${modname} {
@@ -481,23 +492,23 @@ namespace gr {
} /* namespace ${modname} */
} /* namespace gr */
-\#endif /* _QA_${blockname.upper()}_H_ */
+#endif /* _QA_${blockname.upper()}_H_ */
'''
# Python QA code
-Templates['qa_python'] = '''\#!/usr/bin/env python
+Templates['qa_python'] = '''#!/usr/bin/env python
# -*- coding: utf-8 -*-
-${str_to_python_comment($license)}
+${str_to_python_comment(license)}
#
from gnuradio import gr, gr_unittest
from gnuradio import blocks
-#if $lang == 'cpp'
+% if lang == 'cpp':
import ${modname}.${modname}_swig as ${modname}
-#else
+% else:
from ${blockname} import ${blockname}
-#end if
+% endif
class qa_${blockname}(gr_unittest.TestCase):
@@ -519,11 +530,11 @@ if __name__ == '__main__':
Templates['grc_xml'] = '''<?xml version="1.0"?>
<block>
- <name>$blockname</name>
- <key>${modname}_$blockname</key>
- <category>[$modname]</category>
- <import>import $modname</import>
- <make>${modname}.${blockname}(${strip_arg_types_grc($arglist)})</make>
+ <name>${blockname}</name>
+ <key>${modname}_${blockname}</key>
+ <category>[${modname}]</category>
+ <import>import ${modname}</import>
+ <make>${modname}.${blockname}(${strip_arg_types_grc(arglist)})</make>
<!-- Make one 'param' node for every Parameter you want settable from the GUI.
Sub-nodes:
* name
@@ -557,87 +568,86 @@ Templates['grc_xml'] = '''<?xml version="1.0"?>
</block>
'''
-# Usage
-Templates['usage'] = '''
-gr_modtool <command> [options] -- Run <command> with the given options.
-gr_modtool help -- Show a list of commands.
-gr_modtool help <command> -- Shows the help for a given command. '''
-
# SWIG string
-Templates['swig_block_magic'] = """#if $version == '36'
-#if $blocktype != 'noblock'
-GR_SWIG_BLOCK_MAGIC($modname, $blockname);
-#end if
-%include "${modname}_${blockname}.h"
-#else
-%include "${include_dir_prefix}/${blockname}.h"
-#if $blocktype != 'noblock'
-GR_SWIG_BLOCK_MAGIC2($modname, $blockname);
-#end if
-#end if
+Templates['swig_block_magic'] = """% if version == '36':
+% if blocktype != 'noblock':
+GR_SWIG_BLOCK_MAGIC(${modname}, ${blockname});
+% endif
+%%include "${modname}_${blockname}.h"
+% else:
+%%include "${include_dir_prefix}/${blockname}.h"
+ % if blocktype != 'noblock':
+GR_SWIG_BLOCK_MAGIC2(${modname}, ${blockname});
+ % endif
+% endif
"""
## Old stuff
# C++ file of a GR block
Templates['block_cpp36'] = '''/* -*- c++ -*- */
-${str_to_fancyc_comment($license)}
-\#ifdef HAVE_CONFIG_H
-\#include "config.h"
-\#endif
-
-#if $blocktype != 'noblock'
-\#include <gr_io_signature.h>
-#end if
-\#include "${modname}_${blockname}.h"
-
-#if $blocktype == 'noblock'
-${modname}_${blockname}::${modname}_${blockname}(${strip_default_values($arglist)})
+${str_to_fancyc_comment(license)}
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+% if blocktype != 'noblock':
+#include <gr_io_signature.h>
+% endif
+#include "${modname}_${blockname}.h"
+
+% if blocktype == 'noblock':
+${modname}_${blockname}::${modname}_${blockname}(${strip_default_values(arglist)})
{
}
${modname}_${blockname}::~${modname}_${blockname}()
{
}
-#else
+% else:
${modname}_${blockname}_sptr
-${modname}_make_${blockname} (${strip_default_values($arglist)})
+${modname}_make_${blockname} (${strip_default_values(arglist)})
{
- return gnuradio::get_initial_sptr (new ${modname}_${blockname}(${strip_arg_types($arglist)}));
+ return gnuradio::get_initial_sptr (new ${modname}_${blockname}(${strip_arg_types(arglist)}));
}
-#if $blocktype == 'decimator'
-#set $decimation = ', <+decimation+>'
-#else if $blocktype == 'interpolator'
-#set $decimation = ', <+interpolation+>'
-#else
-#set $decimation = ''
-#end if
-#if $blocktype == 'sink'
-#set $inputsig = '0, 0, 0'
-#else
-#set $inputsig = '<+MIN_IN+>, <+MAX_IN+>, sizeof(<+ITYPE+>)'
-#end if
-#if $blocktype == 'source'
-#set $outputsig = '0, 0, 0'
-#else
-#set $outputsig = '<+MIN_OUT+>, <+MAX_OUT+>, sizeof(<+OTYPE+>)'
-#end if
+<%
+ if blocktype == 'interpolator':
+ deciminterp = ', <+interpolation+>'
+ elif blocktype == 'decimator':
+ deciminterp = ', <+decimation+>'
+ else:
+ deciminterp = ''
+ if arglist == '':
+ arglistsep = ''
+ else:
+ arglistsep = ', '
+ if blocktype == 'source':
+ inputsig = '0, 0, 0'
+ else:
+ inputsig = '<+MIN_IN+>, <+MAX_IN+>, sizeof(<+ITYPE+>)'
+ endif
+ if blocktype == 'sink':
+ outputsig = '0, 0, 0'
+ else:
+ outputsig = '<+MIN_OUT+>, <+MAX_OUT+>, sizeof(<+OTYPE+>)'
+ endif
+%>
/*
* The private constructor
*/
-${modname}_${blockname}::${modname}_${blockname} (${strip_default_values($arglist)})
+${modname}_${blockname}::${modname}_${blockname} (${strip_default_values(arglist)})
: gr_${grblocktype} ("${blockname}",
- gr_make_io_signature($inputsig),
- gr_make_io_signature($outputsig)$decimation)
+ gr_make_io_signature(${inputsig}),
+ gr_make_io_signature(${outputsig})${deciminterp})
{
-#if $blocktype == 'hier'
+% if blocktype == 'hier'
connect(self(), 0, d_firstblock, 0);
// <+connect other blocks+>
connect(d_lastblock, 0, self(), 0);
-#else
+% else:
// Put in <+constructor stuff+> here
-#end if
+% endif
}
@@ -648,10 +658,10 @@ ${modname}_${blockname}::~${modname}_${blockname}()
{
// Put in <+destructor stuff+> here
}
-#end if
+% endif
-#if $blocktype == 'general'
+% if blocktype == 'general'
void
${modname}_${blockname}::forecast (int noutput_items, gr_vector_int &ninput_items_required)
{
@@ -675,9 +685,8 @@ ${modname}_${blockname}::general_work (int noutput_items,
// Tell runtime system how many output items we produced.
return noutput_items;
}
-#else if $blocktype == 'hier' or $blocktype == 'noblock'
-#pass
-#else
+% elif blocktype == 'hier' or $blocktype == 'noblock':
+% else:
int
${modname}_${blockname}::work(int noutput_items,
gr_vector_const_void_star &input_items,
@@ -691,51 +700,51 @@ ${modname}_${blockname}::work(int noutput_items,
// Tell runtime system how many output items we produced.
return noutput_items;
}
-#end if
+% endif
'''
# Block definition header file (for include/)
Templates['block_h36'] = '''/* -*- c++ -*- */
-${str_to_fancyc_comment($license)}
+${str_to_fancyc_comment(license)}
-\#ifndef INCLUDED_${modname.upper()}_${blockname.upper()}_H
-\#define INCLUDED_${modname.upper()}_${blockname.upper()}_H
+#ifndef INCLUDED_${modname.upper()}_${blockname.upper()}_H
+#define INCLUDED_${modname.upper()}_${blockname.upper()}_H
-\#include <${modname}_api.h>
-#if $blocktype == 'noblock'
-class ${modname.upper()}_API $blockname
+#include <${modname}_api.h>
+% if blocktype == 'noblock'
+class ${modname.upper()}_API ${blockname}
{
${blockname}(${arglist});
~${blockname}();
private:
};
-#else
-\#include <gr_${grblocktype}.h>
+% else:
+#include <gr_${grblocktype}.h>
class ${modname}_${blockname};
typedef boost::shared_ptr<${modname}_${blockname}> ${modname}_${blockname}_sptr;
-${modname.upper()}_API ${modname}_${blockname}_sptr ${modname}_make_${blockname} ($arglist);
+${modname.upper()}_API ${modname}_${blockname}_sptr ${modname}_make_${blockname} (${arglist});
/*!
* \\brief <+description+>
* \ingroup ${modname}
*
*/
-class ${modname.upper()}_API ${modname}_${blockname} : public gr_$grblocktype
+class ${modname.upper()}_API ${modname}_${blockname} : public gr_${grblocktype}
{
private:
- friend ${modname.upper()}_API ${modname}_${blockname}_sptr ${modname}_make_${blockname} (${strip_default_values($arglist)});
+ friend ${modname.upper()}_API ${modname}_${blockname}_sptr ${modname}_make_${blockname} (${strip_default_values(arglist)});
- ${modname}_${blockname}(${strip_default_values($arglist)});
+ ${modname}_${blockname}(${strip_default_values(arglist)});
public:
~${modname}_${blockname}();
-#if $blocktype == 'general'
+ % if blocktype == 'general':
void forecast (int noutput_items, gr_vector_int &ninput_items_required);
// Where all the action really happens
@@ -743,43 +752,16 @@ class ${modname.upper()}_API ${modname}_${blockname} : public gr_$grblocktype
gr_vector_int &ninput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items);
-#else if $blocktype == 'hier'
-#pass
-#else
+ % elif blocktype == 'hier':
+ % else:
// Where all the action really happens
int work (int noutput_items,
gr_vector_const_void_star &input_items,
gr_vector_void_star &output_items);
-#end if
+ % endif
};
-#end if
-
-\#endif /* INCLUDED_${modname.upper()}_${blockname.upper()}_H */
-
-'''
+% endif
-# C++ file for QA
-Templates['qa_cpp36'] = '''/* -*- c++ -*- */
-${str_to_fancyc_comment($license)}
-
-\#include <boost/test/unit_test.hpp>
-
-BOOST_AUTO_TEST_CASE(qa_${modname}_${blockname}_t1){
- BOOST_CHECK_EQUAL(2 + 2, 4);
- // TODO BOOST_* test macros here
-}
-
-BOOST_AUTO_TEST_CASE(qa_${modname}_${blockname}_t2){
- BOOST_CHECK_EQUAL(2 + 2, 4);
- // TODO BOOST_* test macros here
-}
+#endif /* INCLUDED_${modname.upper()}_${blockname.upper()}_H */
'''
-
-# Header file for QA
-Templates['qa_cmakeentry36'] = """
-add_executable($basename $filename)
-target_link_libraries($basename gnuradio-$modname \${Boost_LIBRARIES})
-GR_ADD_TEST($basename $basename)
-"""
-
diff --git a/gr-utils/python/modtool/util_functions.py b/gr-utils/python/modtool/util_functions.py
index 9a949c8031..edd98fde8f 100644
--- a/gr-utils/python/modtool/util_functions.py
+++ b/gr-utils/python/modtool/util_functions.py
@@ -20,21 +20,14 @@
#
""" Utility functions for gr_modtool """
+from __future__ import unicode_literals
+
import re
import sys
import readline
# None of these must depend on other modtool stuff!
-def get_command_from_argv(possible_cmds):
- """ Read the requested command from argv. This can't be done with optparse,
- since the option parser isn't defined before the command is known, and
- optparse throws an error."""
- for arg in sys.argv:
- if arg[0] != "-" and arg in possible_cmds:
- return arg
- return None
-
def append_re_line_sequence(filename, linepattern, newline):
""" Detects the re 'linepattern' in the file. After its last occurrence,
paste 'newline'. If the pattern does not exist, append the new line
@@ -82,7 +75,7 @@ def strip_arg_types(string):
string = strip_default_values(string)
return ", ".join(
[part.strip().split(' ')[-1] for part in string.split(',')]
- ).translate(None, '*&')
+ ).translate(str.maketrans('','','*&'))
def strip_arg_types_grc(string):
"""" Strip the argument types from a list of arguments for GRC make tag.
@@ -107,7 +100,7 @@ def get_modname():
regexp = r'(project\s*\(\s*|GR_REGISTER_COMPONENT\(")gr-(?P<modname>[a-zA-Z0-9-_]+)(\s*(CXX)?|" ENABLE)'
try:
modname = re.search(regexp, cmfile, flags=re.MULTILINE).group('modname').strip()
- if modname in modname_trans.keys():
+ if modname in list(modname_trans.keys()):
modname = modname_trans[modname]
return modname
except AttributeError:
@@ -141,7 +134,7 @@ def ask_yes_no(question, default):
""" Asks a binary question. Returns True for yes, False for no.
default is given as a boolean. """
question += {True: ' [Y/n] ', False: ' [y/N] '}[default]
- if raw_input(question).lower() != {True: 'n', False: 'y'}[default]:
+ if input(question).lower() != {True: 'n', False: 'y'}[default]:
return default
else:
return not default
diff --git a/gr-utils/python/utils/CMakeLists.txt b/gr-utils/python/utils/CMakeLists.txt
index 54eba51170..3ce335c4ed 100644
--- a/gr-utils/python/utils/CMakeLists.txt
+++ b/gr-utils/python/utils/CMakeLists.txt
@@ -30,7 +30,6 @@ GR_PYTHON_INSTALL(
pyqt_plot.py
pyqt_filter.py
DESTINATION ${GR_PYTHON_DIR}/gnuradio
- COMPONENT "utils"
)
GR_PYTHON_INSTALL(
@@ -50,7 +49,5 @@ GR_PYTHON_INSTALL(
gr_plot_short
gr_plot_qt
gr_read_file_metadata
- grcc
DESTINATION ${GR_RUNTIME_DIR}
- COMPONENT "utils"
)
diff --git a/gr-utils/python/utils/gr_modtool b/gr-utils/python/utils/gr_modtool
index 1690be207f..f959c91f66 100755
--- a/gr-utils/python/utils/gr_modtool
+++ b/gr-utils/python/utils/gr_modtool
@@ -1,6 +1,6 @@
#!/usr/bin/env python
#
-# Copyright 2012, 2017 Free Software Foundation, Inc.
+# Copyright 2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
@@ -21,24 +21,34 @@
#
""" A tool for editing GNU Radio out-of-tree modules. """
+from __future__ import print_function
+
from gnuradio.modtool import *
+def setup_parser():
+ modules = get_modtool_modules(ModTool.__subclasses__())
+ parser = ModTool.get_parser()
+ subparsers = parser.add_subparsers(title="Commands")
+ epilog = []
+ for module in modules:
+ subparser = subparsers.add_parser(module.name,
+ description=module.description)
+ module.setup_parser(subparser)
+ subparser.set_defaults(module=module)
+ epilog.append(" {:<22}{}".format(module.name, module.description))
+ parser.epilog = '\n'.join(epilog)
+ return parser
+
def main():
""" Here we go. Parse command, choose class and run. """
- cmd_dict = get_class_dict(ModTool.__subclasses__())
- command = get_command_from_argv(cmd_dict.keys())
- if command is None:
- print 'Usage:' + Templates['usage']
- exit(2)
- modtool = cmd_dict[command]()
- try:
- (options, args) = modtool.parser.parse_args()
- modtool.setup(options, args)
- modtool.run()
+ parser = setup_parser()
+ args = parser.parse_args()
+ try:
+ args.module().run(args)
except ModToolException as err:
- print >> sys.stderr, err
+ print(err, file=sys.stderr)
exit(1)
if __name__ == '__main__':
diff --git a/gr-utils/python/utils/gr_plot_char b/gr-utils/python/utils/gr_plot_char
index a2b93a63c6..3199919fa9 100755
--- a/gr-utils/python/utils/gr_plot_char
+++ b/gr-utils/python/utils/gr_plot_char
@@ -20,35 +20,34 @@
# Boston, MA 02110-1301, USA.
#
+from __future__ import print_function
+
try:
import scipy
except ImportError:
- print "Please install SciPy to run this script (http://www.scipy.org/)"
- raise SystemExit, 1
+ print("Please install SciPy to run this script (http://www.scipy.org/)")
+ raise SystemExit(1)
-from optparse import OptionParser
+from argparse import ArgumentParser
from gnuradio.plot_data import plot_data
def main():
- usage="%prog: [options] input_filenames"
description = "Takes a GNU Radio byte/char binary file and displays the samples versus time. You can set the block size to specify how many points to read in at a time and the start position in the file. By default, the system assumes a sample rate of 1, so in time, each sample is plotted versus the sample number. To set a true time axis, set the sample rate (-R or --sample-rate) to the sample rate used when capturing the samples."
- parser = OptionParser(conflict_handler="resolve", usage=usage, description=description)
- parser.add_option("-B", "--block", type="int", default=1000,
- help="Specify the block size [default=%default]")
- parser.add_option("-s", "--start", type="int", default=0,
- help="Specify where to start in the file [default=%default]")
- parser.add_option("-R", "--sample-rate", type="float", default=1.0,
- help="Set the sampler rate of the data [default=%default]")
-
- (options, args) = parser.parse_args ()
- if len(args) < 1:
- parser.print_help()
- raise SystemExit, 1
- filenames = args
-
- datatype=scipy.int8
- dc = plot_data(datatype, filenames, options)
+ parser = ArgumentParser(conflict_handler="resolve", description=description)
+ parser.add_argument("-B", "--block", type=int, default=1000,
+ help="Specify the block size [default=%(default)r]")
+ parser.add_argument("-s", "--start", type=int, default=0,
+ help="Specify where to start in the file [default=%(default)r]")
+ parser.add_argument("-R", "--sample-rate", type=float, default=1.0,
+ help="Set the sampler rate of the data [default=%(default)r]")
+ parser.add_argument("files", metavar="FILE", nargs="+",
+ help="Input file with complex samples")
+
+ args = parser.parse_args()
+
+ datatype = scipy.int8
+ dc = plot_data(datatype, args.files, args)
if __name__ == "__main__":
try:
diff --git a/gr-utils/python/utils/gr_plot_const b/gr-utils/python/utils/gr_plot_const
index e2580dd58f..2ec54c3585 100755
--- a/gr-utils/python/utils/gr_plot_const
+++ b/gr-utils/python/utils/gr_plot_const
@@ -20,20 +20,22 @@
# Boston, MA 02110-1301, USA.
#
+from __future__ import print_function
+
try:
import scipy
except ImportError:
- print "Please install SciPy to run this script (http://www.scipy.org/)"
- raise SystemExit, 1
+ print("Please install SciPy to run this script (http://www.scipy.org/)")
+ raise SystemExit(1)
try:
from pylab import *
from matplotlib.font_manager import fontManager, FontProperties
except ImportError:
- print "Please install Matplotlib to run this script (http://matplotlib.sourceforge.net/)"
- raise SystemExit, 1
+ print("Please install Matplotlib to run this script (http://matplotlib.sourceforge.net/)")
+ raise SystemExit(1)
-from optparse import OptionParser
+from argparse import ArgumentParser
class draw_constellation:
def __init__(self, filename, options):
@@ -83,7 +85,7 @@ class draw_constellation:
try:
iq = scipy.fromfile(self.hfile, dtype=self.datatype, count=self.block_length)
except MemoryError:
- print "End of File"
+ print("End of File")
else:
# retesting length here as newer version of scipy does not throw a MemoryError, just
# returns a zero-length array
@@ -94,7 +96,7 @@ class draw_constellation:
self.time = scipy.array([i*(1/self.sample_rate) for i in range(len(self.reals))])
return True
else:
- print "End of File"
+ print("End of File")
return False
def make_plots(self):
@@ -215,36 +217,29 @@ class draw_constellation:
def find(item_in, list_search):
try:
- return list_search.index(item_in) != None
+ return list_search.index(item_in) != None
except ValueError:
- return False
+ return False
def main():
- usage="%prog: [options] input_filename"
description = "Takes a GNU Radio complex binary file and displays the I&Q data versus time and the constellation plot (I vs. Q). You can set the block size to specify how many points to read in at a time and the start position in the file. By default, the system assumes a sample rate of 1, so in time, each sample is plotted versus the sample number. To set a true time axis, set the sample rate (-R or --sample-rate) to the sample rate used when capturing the samples."
- parser = OptionParser(conflict_handler="resolve", usage=usage, description=description)
- parser.add_option("-B", "--block", type="int", default=1000,
- help="Specify the block size [default=%default]")
- parser.add_option("-s", "--start", type="int", default=0,
- help="Specify where to start in the file [default=%default]")
- parser.add_option("-R", "--sample-rate", type="float", default=1.0,
- help="Set the sampler rate of the data [default=%default]")
-
- (options, args) = parser.parse_args ()
- if len(args) != 1:
- parser.print_help()
- raise SystemExit, 1
- filename = args[0]
+ parser = ArgumentParser(conflict_handler="resolve", description=description)
+ parser.add_argument("-B", "--block", type=int, default=1000,
+ help="Specify the block size [default=%(default)r]")
+ parser.add_argument("-s", "--start", type=int, default=0,
+ help="Specify where to start in the file [default=%(default)r]")
+ parser.add_argument("-R", "--sample-rate", type=float, default=1.0,
+ help="Set the sampler rate of the data [default=%(default)r]")
+ parser.add_argument("file", metavar="FILE",
+ help="Input file with complex samples")
+ args = parser.parse_args()
- dc = draw_constellation(filename, options)
+ dc = draw_constellation(args.file, args)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
-
-
-
diff --git a/gr-utils/python/utils/gr_plot_fft b/gr-utils/python/utils/gr_plot_fft
index 4343481645..59fc88b994 100644
--- a/gr-utils/python/utils/gr_plot_fft
+++ b/gr-utils/python/utils/gr_plot_fft
@@ -27,13 +27,9 @@ from gnuradio.plot_fft_base import plot_fft_base
def main():
parser = plot_fft_base.setup_options()
- (options, args) = parser.parse_args ()
- if len(args) != 1:
- parser.print_help()
- raise SystemExit, 1
- filename = args[0]
+ args = parser.parse_args()
- dc = plot_fft_base(options.data_type, filename, options)
+ dc = plot_fft_base(args.data_type, args.file, args)
if __name__ == "__main__":
try:
diff --git a/gr-utils/python/utils/gr_plot_fft_c b/gr-utils/python/utils/gr_plot_fft_c
index 43e808d95a..48d3218586 100755
--- a/gr-utils/python/utils/gr_plot_fft_c
+++ b/gr-utils/python/utils/gr_plot_fft_c
@@ -26,15 +26,12 @@ from gnuradio.plot_fft_base import plot_fft_base
def main():
parser = plot_fft_base.setup_options()
- parser.remove_option("--data-type")
+ parser.add_argument("-d", "--data-type", default="complex64",
+ choices=("complex64", ))
- (options, args) = parser.parse_args ()
- if len(args) != 1:
- parser.print_help()
- raise SystemExit, 1
- filename = args[0]
+ args = parser.parse_args()
- dc = plot_fft_base("complex64", filename, options)
+ dc = plot_fft_base("complex64", args.file, args)
if __name__ == "__main__":
try:
diff --git a/gr-utils/python/utils/gr_plot_fft_f b/gr-utils/python/utils/gr_plot_fft_f
index dee9b17dea..d1791419bb 100755
--- a/gr-utils/python/utils/gr_plot_fft_f
+++ b/gr-utils/python/utils/gr_plot_fft_f
@@ -26,15 +26,11 @@ from gnuradio.plot_fft_base import plot_fft_base
def main():
parser = plot_fft_base.setup_options()
- parser.remove_option("--data-type")
+ parser.add_argument("-d", "--data-type", default="float32",
+ choices=("float32", ))
+ args = parser.parse_args()
- (options, args) = parser.parse_args ()
- if len(args) != 1:
- parser.print_help()
- raise SystemExit, 1
- filename = args[0]
-
- dc = plot_fft_base("float32", filename, options)
+ dc = plot_fft_base("float32", args.file, args)
if __name__ == "__main__":
try:
diff --git a/gr-utils/python/utils/gr_plot_float b/gr-utils/python/utils/gr_plot_float
index 22806e48ae..4fd86549e2 100755
--- a/gr-utils/python/utils/gr_plot_float
+++ b/gr-utils/python/utils/gr_plot_float
@@ -20,35 +20,34 @@
# Boston, MA 02110-1301, USA.
#
+from __future__ import print_function
+
try:
import scipy
except ImportError:
- print "Please install SciPy to run this script (http://www.scipy.org/)"
- raise SystemExit, 1
+ print("Please install SciPy to run this script (http://www.scipy.org/)")
+ raise SystemExit(1)
-from optparse import OptionParser
+from argparse import ArgumentParser
from gnuradio.plot_data import plot_data
def main():
- usage="%prog: [options] input_filenames"
description = "Takes a GNU Radio floating point binary file and displays the samples versus time. You can set the block size to specify how many points to read in at a time and the start position in the file. By default, the system assumes a sample rate of 1, so in time, each sample is plotted versus the sample number. To set a true time axis, set the sample rate (-R or --sample-rate) to the sample rate used when capturing the samples."
- parser = OptionParser(conflict_handler="resolve", usage=usage, description=description)
- parser.add_option("-B", "--block", type="int", default=1000,
- help="Specify the block size [default=%default]")
- parser.add_option("-s", "--start", type="int", default=0,
- help="Specify where to start in the file [default=%default]")
- parser.add_option("-R", "--sample-rate", type="float", default=1.0,
- help="Set the sampler rate of the data [default=%default]")
+ parser = ArgumentParser(conflict_handler="resolve", description=description)
+ parser.add_argument("-B", "--block", type=int, default=1000,
+ help="Specify the block size [default=%(default)r]")
+ parser.add_argument("-s", "--start", type=int, default=0,
+ help="Specify where to start in the file [default=%(default)r]")
+ parser.add_argument("-R", "--sample-rate", type=float, default=1.0,
+ help="Set the sampler rate of the data [default=%(default)r]")
+ parser.add_argument("file", metavar="FILE", nargs='+',
+ help="Input file with samples")
- (options, args) = parser.parse_args ()
- if len(args) < 1:
- parser.print_help()
- raise SystemExit, 1
- filenames = args
+ args = parser.parse_args()
datatype=scipy.float32
- dc = plot_data(datatype, filenames, options)
+ dc = plot_data(datatype, args.file, args)
if __name__ == "__main__":
try:
diff --git a/gr-utils/python/utils/gr_plot_int b/gr-utils/python/utils/gr_plot_int
index 355ddf0189..b4051fa15f 100755
--- a/gr-utils/python/utils/gr_plot_int
+++ b/gr-utils/python/utils/gr_plot_int
@@ -23,32 +23,29 @@
try:
import scipy
except ImportError:
- print "Please install SciPy to run this script (http://www.scipy.org/)"
- raise SystemExit, 1
+ print("Please install SciPy to run this script (http://www.scipy.org/)")
+ raise SystemExit(1)
-from optparse import OptionParser
+from argparse import ArgumentParser
from gnuradio.plot_data import plot_data
def main():
- usage="%prog: [options] input_filenames"
description = "Takes a GNU Radio integer binary file and displays the samples versus time. You can set the block size to specify how many points to read in at a time and the start position in the file. By default, the system assumes a sample rate of 1, so in time, each sample is plotted versus the sample number. To set a true time axis, set the sample rate (-R or --sample-rate) to the sample rate used when capturing the samples."
- parser = OptionParser(conflict_handler="resolve", usage=usage, description=description)
- parser.add_option("-B", "--block", type="int", default=1000,
- help="Specify the block size [default=%default]")
- parser.add_option("-s", "--start", type="int", default=0,
- help="Specify where to start in the file [default=%default]")
- parser.add_option("-R", "--sample-rate", type="float", default=1.0,
- help="Set the sampler rate of the data [default=%default]")
+ parser = ArgumentParser(conflict_handler="resolve", description=description)
+ parser.add_argument("-B", "--block", type=int, default=1000,
+ help="Specify the block size [default=%(default)r]")
+ parser.add_argument("-s", "--start", type=int, default=0,
+ help="Specify where to start in the file [default=%(default)r]")
+ parser.add_argument("-R", "--sample-rate", type=float, default=1.0,
+ help="Set the sampler rate of the data [default=%(default)r]")
+ parser.add_argument("file", metavar="FILE", nargs='+',
+ help="Input file");
- (options, args) = parser.parse_args ()
- if len(args) < 1:
- parser.print_help()
- raise SystemExit, 1
- filenames = args
+ args = parser.parse_args()
datatype=scipy.int32
- dc = plot_data(datatype, filenames, options)
+ dc = plot_data(datatype, args.file, args)
if __name__ == "__main__":
try:
diff --git a/gr-utils/python/utils/gr_plot_iq b/gr-utils/python/utils/gr_plot_iq
index bf8077b6b4..f27f75d412 100755
--- a/gr-utils/python/utils/gr_plot_iq
+++ b/gr-utils/python/utils/gr_plot_iq
@@ -20,19 +20,21 @@
# Boston, MA 02110-1301, USA.
#
+from __future__ import print_function
+
try:
import scipy
except ImportError:
- print "Please install SciPy to run this script (http://www.scipy.org/)"
- raise SystemExit, 1
+ print("Please install SciPy to run this script (http://www.scipy.org/)")
+ raise SystemExit(1)
try:
from pylab import *
except ImportError:
- print "Please install Matplotlib to run this script (http://matplotlib.sourceforge.net/)"
- raise SystemExit, 1
+ print("Please install Matplotlib to run this script (http://matplotlib.sourceforge.net/)")
+ raise SystemExit(1)
-from optparse import OptionParser
+from argparse import ArgumentParser
class draw_iq:
def __init__(self, filename, options):
@@ -81,7 +83,7 @@ class draw_iq:
try:
self.iq = scipy.fromfile(self.hfile, dtype=self.datatype, count=self.block_length)
except MemoryError:
- print "End of File"
+ print("End of File")
else:
self.reals = scipy.array([r.real for r in self.iq])
self.imags = scipy.array([i.imag for i in self.iq])
@@ -144,35 +146,29 @@ class draw_iq:
def find(item_in, list_search):
try:
- return list_search.index(item_in) != None
+ return list_search.index(item_in) != None
except ValueError:
- return False
+ return False
def main():
- usage="%prog: [options] input_filename"
description = "Takes a GNU Radio complex binary file and displays the I&Q data versus time. You can set the block size to specify how many points to read in at a time and the start position in the file. By default, the system assumes a sample rate of 1, so in time, each sample is plotted versus the sample number. To set a true time axis, set the sample rate (-R or --sample-rate) to the sample rate used when capturing the samples."
- parser = OptionParser(conflict_handler="resolve", usage=usage, description=description)
- parser.add_option("-B", "--block", type="int", default=1000,
- help="Specify the block size [default=%default]")
- parser.add_option("-s", "--start", type="int", default=0,
- help="Specify where to start in the file [default=%default]")
- parser.add_option("-R", "--sample-rate", type="float", default=1.0,
- help="Set the sampler rate of the data [default=%default]")
+ parser = ArgumentParser(conflict_handler="resolve", description=description)
+ parser.add_argument("-B", "--block", type=int, default=1000,
+ help="Specify the block size [default=%(default)r]")
+ parser.add_argument("-s", "--start", type=int, default=0,
+ help="Specify where to start in the file [default=%(default)r]")
+ parser.add_argument("-R", "--sample-rate", type=float, default=1.0,
+ help="Set the sampler rate of the data [default=%(default)r]")
+ parser.add_argument("file", metavar="FILE",
+ help="Input file with complex samples")
- (options, args) = parser.parse_args ()
- if len(args) != 1:
- parser.print_help()
- raise SystemExit, 1
- filename = args[0]
+ args = parser.parse_args()
- dc = draw_iq(filename, options)
+ dc = draw_iq(args.file, args)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
-
-
-
diff --git a/gr-utils/python/utils/gr_plot_psd b/gr-utils/python/utils/gr_plot_psd
index 059ca6b645..b052cbfdd7 100644
--- a/gr-utils/python/utils/gr_plot_psd
+++ b/gr-utils/python/utils/gr_plot_psd
@@ -27,13 +27,9 @@ from gnuradio.plot_psd_base import plot_psd_base
def main():
parser = plot_psd_base.setup_options()
- (options, args) = parser.parse_args ()
- if len(args) != 1:
- parser.print_help()
- raise SystemExit, 1
- filename = args[0]
+ args = parser.parse_args()
- dc = plot_psd_base(options.data_type, filename, options)
+ dc = plot_psd_base(args.data_type, args.file, args)
if __name__ == "__main__":
try:
diff --git a/gr-utils/python/utils/gr_plot_psd_c b/gr-utils/python/utils/gr_plot_psd_c
index fff2bff0f2..352a838138 100755
--- a/gr-utils/python/utils/gr_plot_psd_c
+++ b/gr-utils/python/utils/gr_plot_psd_c
@@ -20,22 +20,19 @@
# Boston, MA 02110-1301, USA.
#
-from optparse import OptionParser
+from argparse import ArgumentParser
from gnuradio.plot_psd_base import plot_psd_base
# This is a wrapper program for plot_psd_base specifically for complex data
def main():
parser = plot_psd_base.setup_options()
- parser.remove_option("--data-type")
+ parser.add_argument("-d", "--data-type", default="complex64",
+ choices=("complex64", ))
- (options, args) = parser.parse_args ()
- if len(args) != 1:
- parser.print_help()
- raise SystemExit, 1
- filename = args[0]
+ args = parser.parse_args()
- dc = plot_psd_base("complex64", filename, options)
+ dc = plot_psd_base("complex64", args.file, args)
if __name__ == "__main__":
try:
diff --git a/gr-utils/python/utils/gr_plot_psd_f b/gr-utils/python/utils/gr_plot_psd_f
index ec67994797..ab860e3fb8 100755
--- a/gr-utils/python/utils/gr_plot_psd_f
+++ b/gr-utils/python/utils/gr_plot_psd_f
@@ -20,22 +20,19 @@
# Boston, MA 02110-1301, USA.
#
-from optparse import OptionParser
+from argparse import ArgumentParser
from gnuradio.plot_psd_base import plot_psd_base
# This is a wrapper program for gr_plot_psd specifically for floating point data
def main():
parser = plot_psd_base.setup_options()
- parser.remove_option("--data-type")
+ parser.add_argument("-d", "--data-type", default="complex64",
+ choices=("float32", ))
- (options, args) = parser.parse_args ()
- if len(args) != 1:
- parser.print_help()
- raise SystemExit, 1
- filename = args[0]
+ args = parser.parse_args()
- dc = plot_psd_base("float32", filename, options)
+ dc = plot_psd_base("float32", args.file, args)
if __name__ == "__main__":
try:
diff --git a/gr-utils/python/utils/gr_plot_qt b/gr-utils/python/utils/gr_plot_qt
index 9205d23a7e..854ecc53b8 100755
--- a/gr-utils/python/utils/gr_plot_qt
+++ b/gr-utils/python/utils/gr_plot_qt
@@ -4,34 +4,34 @@ try:
import scipy
from scipy import fftpack
except ImportError:
- print "Please install SciPy to run this script (http://www.scipy.org/)"
- raise SystemExit, 1
+ print("Please install SciPy to run this script (http://www.scipy.org/)")
+ raise SystemExit(1)
try:
from matplotlib import mlab
except ImportError:
- print "Please install Matplotlib to run this script (http://matplotlib.sourceforge.net)"
- raise SystemExit, 1
+ print("Please install Matplotlib to run this script (http://matplotlib.sourceforge.net)")
+ raise SystemExit(1)
try:
from PyQt4 import Qt, QtCore, QtGui
except ImportError:
- print "Please install PyQt4 to run this script (http://www.riverbankcomputing.co.uk/software/pyqt/download)"
- raise SystemExit, 1
+ print("Please install PyQt4 to run this script (http://www.riverbankcomputing.co.uk/software/pyqt/download)")
+ raise SystemExit(1)
try:
import PyQt4.Qwt5 as Qwt
except ImportError:
- print "Please install PyQwt5 to run this script (http://pyqwt.sourceforge.net/)"
- raise SystemExit, 1
+ print("Please install PyQwt5 to run this script (http://pyqwt.sourceforge.net/)")
+ raise SystemExit(1)
try:
# FIXME: re-enable this before committing
#from gnuradio.pyqt_plot import Ui_MainWindow
from gnuradio.pyqt_plot import Ui_MainWindow
except ImportError:
- print "Could not import from pyqt_plot. Please build with \"pyuic4 pyqt_plot.ui -o pyqt_plot.py\""
- raise SystemExit, 1
+ print("Could not import from pyqt_plot. Please build with \"pyuic4 pyqt_plot.ui -o pyqt_plot.py\"")
+ raise SystemExit(1)
import sys, os
from optparse import OptionParser
@@ -284,7 +284,7 @@ class gr_plot_qt(QtGui.QMainWindow):
def open_file(self):
filename = Qt.QFileDialog.getOpenFileName(self, "Open", ".")
if(filename != ""):
- #print filename
+ #print(filename)
self.initialize(filename)
def reload_file(self):
@@ -320,7 +320,7 @@ class gr_plot_qt(QtGui.QMainWindow):
def init_data_input(self):
self.hfile.seek(0, os.SEEK_END)
self.signal_size = self.hfile.tell()/self.sizeof_data
- #print "Sizeof File: ", self.signal_size
+ #print("Sizeof File: ", self.signal_size)
self.hfile.seek(0, os.SEEK_SET)
def get_data(self, start, end):
@@ -338,7 +338,7 @@ class gr_plot_qt(QtGui.QMainWindow):
tstep = 1.0 / self.sample_rate
self.iq = iq
- self.time = [tstep*(self.position + i) for i in xrange(len(self.iq))]
+ self.time = [tstep*(self.position + i) for i in range(len(self.iq))]
self.set_file_pos_box(start, end)
except MemoryError:
diff --git a/gr-utils/python/utils/gr_plot_short b/gr-utils/python/utils/gr_plot_short
index 702a2a94a6..d367ea381f 100755
--- a/gr-utils/python/utils/gr_plot_short
+++ b/gr-utils/python/utils/gr_plot_short
@@ -20,35 +20,34 @@
# Boston, MA 02110-1301, USA.
#
+from __future__ import print_function
+
try:
import scipy
except ImportError:
- print "Please install SciPy to run this script (http://www.scipy.org/)"
- raise SystemExit, 1
+ print("Please install SciPy to run this script (http://www.scipy.org/)")
+ raise SystemExit(1)
-from optparse import OptionParser
+from argparse import ArgumentParser
from gnuradio.plot_data import plot_data
def main():
- usage="%prog: [options] input_filenames"
description = "Takes a GNU Radio short integer binary file and displays the samples versus time. You can set the block size to specify how many points to read in at a time and the start position in the file. By default, the system assumes a sample rate of 1, so in time, each sample is plotted versus the sample number. To set a true time axis, set the sample rate (-R or --sample-rate) to the sample rate used when capturing the samples."
- parser = OptionParser(conflict_handler="resolve", usage=usage, description=description)
- parser.add_option("-B", "--block", type="int", default=1000,
- help="Specify the block size [default=%default]")
- parser.add_option("-s", "--start", type="int", default=0,
- help="Specify where to start in the file [default=%default]")
- parser.add_option("-R", "--sample-rate", type="float", default=1.0,
- help="Set the sampler rate of the data [default=%default]")
+ parser = ArgumentParser(conflict_handler="resolve", description=description)
+ parser.add_argument("-B", "--block", type=int, default=1000,
+ help="Specify the block size [default=%(default)r]")
+ parser.add_argument("-s", "--start", type=int, default=0,
+ help="Specify where to start in the file [default=%(default)r]")
+ parser.add_argument("-R", "--sample-rate", type=float, default=1.0,
+ help="Set the sampler rate of the data [default=%(default)r]")
+ parser.add_argument("files", metavar="FILE", nargs="+",
+ help="Input file with data (int16_t)")
- (options, args) = parser.parse_args ()
- if len(args) < 1:
- parser.print_help()
- raise SystemExit, 1
- filenames = args
+ args = parser.parse_args()
datatype=scipy.int16
- dc = plot_data(datatype, filenames, options)
+ dc = plot_data(datatype, args.files, args)
if __name__ == "__main__":
try:
diff --git a/gr-utils/python/utils/gr_read_file_metadata b/gr-utils/python/utils/gr_read_file_metadata
index 429b38310f..1a94560ad2 100644
--- a/gr-utils/python/utils/gr_read_file_metadata
+++ b/gr-utils/python/utils/gr_read_file_metadata
@@ -20,8 +20,10 @@
# Boston, MA 02110-1301, USA.
#
+from __future__ import print_function
+
import sys
-from optparse import OptionParser
+from argparse import ArgumentParser
import pmt
from gnuradio.blocks import parse_file_metadata
@@ -45,7 +47,7 @@ def main(filename, detached=False):
sys.stderr.write("Could not deserialize header: invalid or corrupt data file.\n")
sys.exit(1)
- print "HEADER {0}".format(nheaders)
+ print("HEADER {0}".format(nheaders))
info = parse_file_metadata.parse_header(header, True)
if(info["extra_len"] > 0):
@@ -59,7 +61,7 @@ def main(filename, detached=False):
sys.stderr.write("Could not deserialize extras: invalid or corrupt data file.\n")
sys.exit(1)
- print "\nExtra Header:"
+ print("\nExtra Header:")
extra_info = parse_file_metadata.parse_extra_dict(extra, info, True)
nheaders += 1
@@ -67,21 +69,17 @@ def main(filename, detached=False):
if(not detached):
nread += info['nbytes']
handle.seek(nread, 0)
- print "\n\n"
+ print("\n\n")
+
if __name__ == "__main__":
- usage="%prog: [options] filename"
description = "Read in a GNU Radio file with meta data, extracts the header and prints it."
- parser = OptionParser(conflict_handler="resolve",
- usage=usage, description=description)
- parser.add_option("-D", "--detached", action="store_true", default=False,
+ parser = ArgumentParser(conflict_handler="resolve", description=description)
+ parser.add_argument("-D", "--detached", action="store_true",
help="Used if header is detached.")
- (options, args) = parser.parse_args ()
-
- if(len(args) < 1):
- sys.stderr.write("No filename given\n")
- sys.exit(1)
+ parser.add_argument("file", metavar="FILE",
+ help="Input file");
+ args = parser.parse_args()
- filename = args[0]
- main(filename, options.detached)
+ main(args.file, args.detached)
diff --git a/gr-utils/python/utils/grcc b/gr-utils/python/utils/grcc
deleted file mode 100755
index b9bd1551b9..0000000000
--- a/gr-utils/python/utils/grcc
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/usr/bin/env python
-#
-# Copyright 2012 Free Software Foundation, Inc.
-#
-# This file is part of GNU Radio
-#
-# GNU Radio is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; either version 3, or (at your option)
-# any later version.
-#
-# GNU Radio is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with GNU Radio; see the file COPYING. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street,
-# Boston, MA 02110-1301, USA.
-#
-
-import os
-import sys
-from optparse import OptionParser
-import warnings
-warnings.simplefilter('ignore')
-
-from gnuradio import gr
-
-try:
- from grc.core.Platform import Platform
-except ImportError:
- from gnuradio.grc.core.Platform import Platform
-
-
-class GRCC:
- def __init__(self, grcfile, out_dir):
- self.out_dir = out_dir
- self.platform = Platform(
- prefs_file=gr.prefs(),
- version=gr.version(),
- version_parts=(gr.major_version(), gr.api_version(), gr.minor_version())
- )
- data = self.platform.parse_flow_graph(grcfile)
-
- self.fg = self.platform.get_new_flow_graph()
- self.fg.import_data(data)
- self.fg.grc_file_path = os.path.abspath(grcfile)
- self.fg.validate()
-
- if not self.fg.is_valid():
- raise StandardError("\n\n".join(
- ["Validation failed:"] + self.fg.get_error_messages()
- ))
-
- self.gen = self.platform.Generator(self.fg, out_dir)
- self.gen.write()
-
- def exec_program(self):
- progname = self.fg.get_option('id')
- os.system("{0}/{1}.py".format(self.out_dir, progname))
-
-
-def main():
- usage="%prog: [options] filename"
- description = "Compiles a GRC file (.grc) into a GNU Radio Python program. The program is stored in ~/.grc_gnuradio by default, but this location can be changed with the -d option."
-
- parser = OptionParser(conflict_handler="resolve", usage=usage, description=description)
- parser.add_option("-d", "--directory", type="string", default='{0}/.grc_gnuradio/'.format(os.environ["HOME"]),
- help="Specify the directory to output the compile program [default=%default]")
- parser.add_option("-e", "--execute", action="store_true", default=False,
- help="Run the program after compiling [default=%default]")
- (options, args) = parser.parse_args ()
-
- if len(args) != 1:
- sys.stderr.write("Please specify a GRC file name to compile.\n")
- sys.exit(1)
-
- try:
- g = GRCC(args[0], options.directory + "/")
- except Exception as e:
- sys.stderr.write(str(e) + "\n")
- sys.stderr.write("Error during file compilation.\n")
- sys.exit(1)
-
- if options.execute:
- g.exec_program()
-
-
-if __name__ == "__main__":
- main()
diff --git a/gr-utils/python/utils/plot_data.py b/gr-utils/python/utils/plot_data.py
index 2ae3b1d5b3..a054147114 100644
--- a/gr-utils/python/utils/plot_data.py
+++ b/gr-utils/python/utils/plot_data.py
@@ -22,21 +22,24 @@
Utility to help plotting data from files.
"""
+from __future__ import print_function
+from __future__ import division
+from __future__ import unicode_literals
+
try:
import scipy
except ImportError:
- print "Please install SciPy to run this script (http://www.scipy.org/)"
- raise SystemExit, 1
+ print("Please install SciPy to run this script (http://www.scipy.org/)")
+ raise SystemExit(1)
try:
from pylab import *
except ImportError:
- print "Please install Matplotlib to run this script (http://matplotlib.sourceforge.net/)"
- raise SystemExit, 1
+ print("Please install Matplotlib to run this script (http://matplotlib.sourceforge.net/)")
+ raise SystemExit(1)
-from optparse import OptionParser
-class plot_data:
+class plot_data(object):
def __init__(self, datatype, filenames, options):
self.hfile = list()
self.legend_text = list()
@@ -87,10 +90,10 @@ class plot_data:
try:
f = scipy.fromfile(hfile, dtype=self.datatype, count=self.block_length)
except MemoryError:
- print "End of File"
+ print("End of File")
else:
self.f = scipy.array(f)
- self.time = scipy.array([i*(1/self.sample_rate) for i in range(len(self.f))])
+ self.time = scipy.array([i*(1 / self.sample_rate) for i in range(len(self.f))])
def make_plots(self):
self.sp_f = self.fig.add_subplot(2,1,1, position=[0.075, 0.2, 0.875, 0.6])
@@ -163,6 +166,6 @@ class plot_data:
def find(item_in, list_search):
try:
- return list_search.index(item_in) != None
+ return list_search.index(item_in) != None
except ValueError:
- return False
+ return False
diff --git a/gr-utils/python/utils/plot_fft_base.py b/gr-utils/python/utils/plot_fft_base.py
index c4bc484d97..5040aefa87 100755..100644
--- a/gr-utils/python/utils/plot_fft_base.py
+++ b/gr-utils/python/utils/plot_fft_base.py
@@ -20,22 +20,26 @@
# Boston, MA 02110-1301, USA.
#
+from __future__ import print_function
+from __future__ import division
+from __future__ import unicode_literals
+
try:
import scipy
from scipy import fftpack
except ImportError:
- print "Please install SciPy to run this script (http://www.scipy.org/)"
- raise SystemExit, 1
+ print("Please install SciPy to run this script (http://www.scipy.org/)")
+ raise SystemExit(1)
try:
from pylab import *
except ImportError:
- print "Please install Python Matplotlib (http://matplotlib.sourceforge.net/) and Python TkInter https://wiki.python.org/moin/TkInter to run this script"
- raise SystemExit, 1
+ print("Please install Python Matplotlib (http://matplotlib.sourceforge.net/) and Python TkInter https://wiki.python.org/moin/TkInter to run this script")
+ raise SystemExit(1)
-from optparse import OptionParser
+from argparse import ArgumentParser
-class plot_fft_base:
+class plot_fft_base(object):
def __init__(self, datatype, filename, options):
self.hfile = open(filename, "r")
self.block_length = options.block
@@ -79,33 +83,33 @@ class plot_fft_base:
show()
def get_data(self):
- self.position = self.hfile.tell()/self.sizeof_data
+ self.position = self.hfile.tell() / self.sizeof_data
self.text_file_pos.set_text("File Position: %d" % (self.position))
try:
self.iq = scipy.fromfile(self.hfile, dtype=self.datatype, count=self.block_length)
except MemoryError:
- print "End of File"
+ print("End of File")
else:
self.iq_fft = self.dofft(self.iq)
tstep = 1.0 / self.sample_rate
- #self.time = scipy.array([tstep*(self.position + i) for i in xrange(len(self.iq))])
- self.time = scipy.array([tstep*(i) for i in xrange(len(self.iq))])
+ #self.time = scipy.array([tstep*(self.position + i) for i in range(len(self.iq))])
+ self.time = scipy.array([tstep*(i) for i in range(len(self.iq))])
self.freq = self.calc_freq(self.time, self.sample_rate)
def dofft(self, iq):
N = len(iq)
iq_fft = scipy.fftpack.fftshift(scipy.fft(iq)) # fft and shift axis
- iq_fft = 20*scipy.log10(abs((iq_fft+1e-15)/N)) # convert to decibels, adjust power
+ iq_fft = 20*scipy.log10(abs((iq_fft+1e-15) / N)) # convert to decibels, adjust power
# adding 1e-15 (-300 dB) to protect against value errors if an item in iq_fft is 0
return iq_fft
def calc_freq(self, time, sample_rate):
N = len(time)
- Fs = 1.0 / (time.max() - time.min())
+ Fs = 1.0 / (time.max( - time.min()))
Fn = 0.5 * sample_rate
- freq = scipy.array([-Fn + i*Fs for i in xrange(N)])
+ freq = scipy.array([-Fn + i*Fs for i in range(N)])
return freq
def make_plots(self):
@@ -209,41 +213,37 @@ class plot_fft_base:
@staticmethod
def setup_options():
- usage="%prog: [options] input_filename"
description = "Takes a GNU Radio complex binary file and displays the I&Q data versus time as well as the frequency domain (FFT) plot. The y-axis values are plotted assuming volts as the amplitude of the I&Q streams and converted into dBm in the frequency domain (the 1/N power adjustment out of the FFT is performed internally). The script plots a certain block of data at a time, specified on the command line as -B or --block. This value defaults to 1000. The start position in the file can be set by specifying -s or --start and defaults to 0 (the start of the file). By default, the system assumes a sample rate of 1, so in time, each sample is plotted versus the sample number. To set a true time and frequency axis, set the sample rate (-R or --sample-rate) to the sample rate used when capturing the samples."
- parser = OptionParser(conflict_handler="resolve", usage=usage, description=description)
- parser.add_option("-d", "--data-type", type="string", default="complex64",
- help="Specify the data type (complex64, float32, (u)int32, (u)int16, (u)int8) [default=%default]")
- parser.add_option("-B", "--block", type="int", default=1000,
- help="Specify the block size [default=%default]")
- parser.add_option("-s", "--start", type="int", default=0,
- help="Specify where to start in the file [default=%default]")
- parser.add_option("-R", "--sample-rate", type="float", default=1.0,
- help="Set the sampler rate of the data [default=%default]")
+ parser = ArgumentParser(conflict_handler="resolve", description=description)
+ parser.add_argument("-d", "--data-type", default="complex64",
+ choices=("complex64", "float32", "uint32", "int32", "uint16",
+ "int16", "uint8", "int8"),
+ help="Specify the data type [default=%(default)r]")
+ parser.add_argument("-B", "--block", type=int, default=1000,
+ help="Specify the block size [default=%(default)r]")
+ parser.add_argument("-s", "--start", type=int, default=0,
+ help="Specify where to start in the file [default=%(default)r]")
+ parser.add_argument("-R", "--sample-rate", type=float, default=1.0,
+ help="Set the sampler rate of the data [default=%(default)r]")
+ parser.add_argument("file", metavar="FILE",
+ help="Input file with samples")
return parser
def find(item_in, list_search):
try:
- return list_search.index(item_in) != None
+ return list_search.index(item_in) != None
except ValueError:
- return False
+ return False
def main():
parser = plot_fft_base.setup_options()
- (options, args) = parser.parse_args ()
- if len(args) != 1:
- parser.print_help()
- raise SystemExit, 1
- filename = args[0]
+ args = parser.parse_args()
- dc = plot_fft_base(options.data_type, filename, options)
+ dc = plot_fft_base(args.data_type, args.file, args)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
-
-
-
diff --git a/gr-utils/python/utils/plot_psd_base.py b/gr-utils/python/utils/plot_psd_base.py
index fe3c9e12b7..0a0f3cab34 100755..100644
--- a/gr-utils/python/utils/plot_psd_base.py
+++ b/gr-utils/python/utils/plot_psd_base.py
@@ -20,24 +20,28 @@
# Boston, MA 02110-1301, USA.
#
+from __future__ import print_function
+from __future__ import division
+from __future__ import unicode_literals
+
try:
import scipy
from scipy import fftpack
except ImportError:
- print "Please install SciPy to run this script (http://www.scipy.org/)"
- raise SystemExit, 1
+ print("Please install SciPy to run this script (http://www.scipy.org/)")
+ raise SystemExit(1)
try:
from pylab import *
except ImportError:
- print "Please install Matplotlib to run this script (http://matplotlib.sourceforge.net/)"
- raise SystemExit, 1
+ print("Please install Matplotlib to run this script (http://matplotlib.sourceforge.net/)")
+ raise SystemExit(1)
-from optparse import OptionParser
+from argparse import ArgumentParser
from scipy import log10
-from gnuradio.eng_option import eng_option
+from gnuradio.eng_arg import eng_float, intx
-class plot_psd_base:
+class plot_psd_base(object):
def __init__(self, datatype, filename, options):
self.hfile = open(filename, "r")
self.block_length = options.block
@@ -87,30 +91,30 @@ class plot_psd_base:
show()
def get_data(self):
- self.position = self.hfile.tell()/self.sizeof_data
+ self.position = self.hfile.tell() / self.sizeof_data
self.text_file_pos.set_text("File Position: %d" % self.position)
try:
self.iq = scipy.fromfile(self.hfile, dtype=self.datatype, count=self.block_length)
except MemoryError:
- print "End of File"
+ print("End of File")
return False
else:
# retesting length here as newer version of scipy does not throw a MemoryError, just
# returns a zero-length array
if(len(self.iq) > 0):
tstep = 1.0 / self.sample_rate
- #self.time = scipy.array([tstep*(self.position + i) for i in xrange(len(self.iq))])
- self.time = scipy.array([tstep*(i) for i in xrange(len(self.iq))])
+ #self.time = scipy.array([tstep*(self.position + i) for i in range(len(self.iq))])
+ self.time = scipy.array([tstep*(i) for i in range(len(self.iq))])
self.iq_psd, self.freq = self.dopsd(self.iq)
return True
else:
- print "End of File"
+ print("End of File")
return False
def dopsd(self, iq):
''' Need to do this here and plot later so we can do the fftshift '''
- overlap = self.psdfftsize/4
+ overlap = self.psdfftsize / 4
winfunc = scipy.blackman
psd,freq = mlab.psd(iq, self.psdfftsize, self.sample_rate,
window = lambda d: d*winfunc(self.psdfftsize),
@@ -174,7 +178,7 @@ class plot_psd_base:
self.sp_psd.set_xlim([f.min(), f.max()])
def draw_spec(self, t, s):
- overlap = self.specfftsize/4
+ overlap = self.specfftsize / 4
winfunc = scipy.blackman
self.sp_spec.clear()
self.sp_spec.specgram(s, self.specfftsize, self.sample_rate,
@@ -244,49 +248,44 @@ class plot_psd_base:
@staticmethod
def setup_options():
- usage="%prog: [options] input_filename"
description = "Takes a GNU Radio binary file (with specified data type using --data-type) and displays the I&Q data versus time as well as the power spectral density (PSD) plot. The y-axis values are plotted assuming volts as the amplitude of the I&Q streams and converted into dBm in the frequency domain (the 1/N power adjustment out of the FFT is performed internally). The script plots a certain block of data at a time, specified on the command line as -B or --block. The start position in the file can be set by specifying -s or --start and defaults to 0 (the start of the file). By default, the system assumes a sample rate of 1, so in time, each sample is plotted versus the sample number. To set a true time and frequency axis, set the sample rate (-R or --sample-rate) to the sample rate used when capturing the samples. Finally, the size of the FFT to use for the PSD and spectrogram plots can be set independently with --psd-size and --spec-size, respectively. The spectrogram plot does not display by default and is turned on with -S or --enable-spec."
- parser = OptionParser(option_class=eng_option, conflict_handler="resolve",
- usage=usage, description=description)
- parser.add_option("-d", "--data-type", type="string", default="complex64",
- help="Specify the data type (complex64, float32, (u)int32, (u)int16, (u)int8) [default=%default]")
- parser.add_option("-B", "--block", type="int", default=8192,
- help="Specify the block size [default=%default]")
- parser.add_option("-s", "--start", type="int", default=0,
- help="Specify where to start in the file [default=%default]")
- parser.add_option("-R", "--sample-rate", type="eng_float", default=1.0,
- help="Set the sampler rate of the data [default=%default]")
- parser.add_option("", "--psd-size", type="int", default=1024,
- help="Set the size of the PSD FFT [default=%default]")
- parser.add_option("", "--spec-size", type="int", default=256,
- help="Set the size of the spectrogram FFT [default=%default]")
- parser.add_option("-S", "--enable-spec", action="store_true", default=False,
- help="Turn on plotting the spectrogram [default=%default]")
+ parser = ArgumentParser(conflict_handler="resolve", description=description)
+ parser.add_argument("-d", "--data-type", default="complex64",
+ choices=("complex64", "float32", "int32", "uint32", "int16",
+ "uint16", "int8", "uint8" ),
+ help="Specify the data type [default=%(default)r]")
+ parser.add_argument("-B", "--block", type=int, default=8192,
+ help="Specify the block size [default=%(default)r]")
+ parser.add_argument("-s", "--start", type=int, default=0,
+ help="Specify where to start in the file [default=%(default)r]")
+ parser.add_argument("-R", "--sample-rate", type=eng_float, default=1.0,
+ help="Set the sampler rate of the data [default=%(default)r]")
+ parser.add_argument("--psd-size", type=int, default=1024,
+ help="Set the size of the PSD FFT [default=%(default)r]")
+ parser.add_argument("--spec-size", type=int, default=256,
+ help="Set the size of the spectrogram FFT [default=%(default)r]")
+ parser.add_argument("-S", "--enable-spec", action="store_true",
+ help="Turn on plotting the spectrogram [default=%(default)r]")
+ parser.add_argument("file", metavar="FILE",
+ help="Input file with samples")
return parser
def find(item_in, list_search):
try:
- return list_search.index(item_in) != None
+ return list_search.index(item_in) != None
except ValueError:
- return False
+ return False
def main():
parser = plot_psd_base.setup_options()
- (options, args) = parser.parse_args ()
- if len(args) != 1:
- parser.print_help()
- raise SystemExit, 1
- filename = args[0]
+ args = parser.parse_args()
- dc = plot_psd_base(options.data_type, filename, options)
+ dc = plot_psd_base(args.data_type, args.file, args)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass
-
-
-
diff --git a/gr-utils/python/utils/pyqt_filter.py b/gr-utils/python/utils/pyqt_filter.py
index 0c781f2347..fac17644d3 100644
--- a/gr-utils/python/utils/pyqt_filter.py
+++ b/gr-utils/python/utils/pyqt_filter.py
@@ -7,6 +7,7 @@
#
# WARNING! All changes made in this file will be lost!
+from __future__ import unicode_literals
from PyQt4 import QtCore, QtGui
class Ui_MainWindow(object):
diff --git a/gr-utils/python/utils/pyqt_plot.py b/gr-utils/python/utils/pyqt_plot.py
index 5650135abf..80711b4e88 100644
--- a/gr-utils/python/utils/pyqt_plot.py
+++ b/gr-utils/python/utils/pyqt_plot.py
@@ -7,6 +7,7 @@
#
# WARNING! All changes made in this file will be lost!
+from __future__ import unicode_literals
from PyQt4 import QtCore, QtGui
class Ui_MainWindow(object):