set_name()¶
动态定义 name
属性。这个方法很少需要,因为唯一有意义的使用场景是当一个 recipe 被共享并用于使用同一个 recipe 创建不同的包时。在大多数情况下,推荐的方法是在 recipe 中定义 name = "mypkg"
属性。
这个方法仅在 recipe 被导出到缓存时执行(例如 conan create
和 conan export
),以及在 recipe 被本地使用时(例如 conan install .
)。在所有其他情况下,包的名称是完全确定的,set_name()
不会被调用,因此不要依赖它来实现除定义 self.name
值以外的任何其他功能。
如果当前的包名是在一个 *name.txt* 文件中定义的,那么可以这样做:
from conan import ConanFile
from conan.tools.files import load
class Pkg(ConanFile):
def set_name(self):
# This will execute relatively to the current user directory (name.txt in cwd)
self.name = load(self, "name.txt")
# if "name.txt" is located relative to the conanfile.py better do:
self.name = load(self, os.path.join(self.recipe_folder, "name.txt"))
包名也可以通过命令行参数 --name=xxxx
为某些命令定义。如果我们想优先使用命令行参数,应该这样做:
from conan import ConanFile
from conan.tools.files import load
class Pkg(ConanFile):
def set_name(self):
# Command line ``--name=xxxx`` will be assigned first to self.name and have priority
self.name = self.name or load(self, "name.txt")
set_name() 方法可以决定定义 name
值,而不考虑潜在的 --name=xxx
命令行参数,后者甚至可以被 set_name()
完全忽略。开发者有责任提供一个正确的 set_name()
方法。
def set_name(self):
# This will always assign "pkg" as name, ignoring ``--name`` command line argument
# and without erroring or warning
self.name = "pkg"
如果提供了命令行参数 --name=xxx
,它将被初始化到 self.name
属性中,因此 set_name()
方法可以读取并使用它。
def set_name(self):
# Takes the provided command line ``--name`` argument and creates a name appending to
# it the ".extra" string
self.name = self.name + ".extra"
警告
set_name() 方法是 name
属性的替代方案。不建议或不支持同时定义 name
属性和 set_name()
方法。