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

aby*_*s.7 5 python cmake protocol-buffers

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

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

我怎样才能做到这一点?

PS我已经尝试从CMake:如何获取目录的所有子目录的名称?(将GLOB更改为GLOB_RECURSE),但它仅返回包含文件的子目录。我无法package1从上面的示例获取subdir。

Don*_*ion 5

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

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

或使用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)
Run Code Online (Sandbox Code Playgroud)


Fra*_*ser 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)
Run Code Online (Sandbox Code Playgroud)