如何在cmake中当前目录的所有子目录中生成__init__.py?

时间:2012-07-12 09:43:20

标签: python cmake protocol-buffers

我使用CMake的树外构建。 我有一个CMake自定义命令,从原型文件生成* _pb2.py文件。 由于原始文件可能驻留在未知数量的子目录(包名称空间)中,如$SRC/package1/package2/file.proto,因此构建目录将包含$BLD/package1/package2/file_pb2.py之类的内容。

我想从自动生成的* _pb2.py文件中隐式生成包,因此,我想在所有子文件夹($BLD/package1$BLD/package1/package2等中自动生成__init__.py文件。)然后安装它们。

我该怎么做?

PS 我已尝试从CMake : How to get the name of all subdirectories of a directory?(已更改 GLOB GLOB_RECURSE )的宏,但它只返回包含文件的子目录。我无法从上面的示例中获取package1子目录。

2 个答案:

答案 0 :(得分:4)

如果你在* NIX操作系统(包括mac)下工作,你可以使用shell find命令,如:

ROOT="./"
for DIR in $(find $ROOT -type d); do
    touch $DIR/__init__.py
done

或使用python脚本:

from os.path import isdir, walk, join

root = "/path/to/project"
finit = '__init__.py'
def visitor(arg, dirname, fnames):
    fnames = [fname for fname in fnames if isdir(fname)]
    # here you could do some additional checks ...
    print "adding %s to : %s" %(finit, dirname)
    with open(join(dirname, finit), 'w') as file_: file_.write('')

walk(root, visitor, None)

答案 1 :(得分:2)

以下内容应该为您提供变量AllPaths中所需的目录列表:

# Get paths to all .py files (relative to build dir)
file(GLOB_RECURSE SubDirs RELATIVE ${CMAKE_BINARY_DIR} "${CMAKE_BINARY_DIR}/*.py")
# Clear the variable AllPaths ready to take the list of results
set(AllPaths)
foreach(SubDir ${SubDirs})
  # Strip the filename from the path
  get_filename_component(SubDir ${SubDir} PATH)
  # Change the path to a semi-colon separated list
  string(REPLACE "/" ";" PathParts ${SubDir})
  # Incrementally rebuild path, appending each partial path to list of results
  set(RebuiltPath ${CMAKE_BINARY_DIR})
  foreach(PathPart ${PathParts})
    set(RebuiltPath "${RebuiltPath}/${PathPart}")
    set(AllPaths ${AllPaths} ${RebuiltPath})
  endforeach()
endforeach()
# Remove duplicates
list(REMOVE_DUPLICATES AllPaths)