idf.py 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  1. #!/usr/bin/env python
  2. #
  3. # 'idf.py' is a top-level config/build command line tool for ESP-IDF
  4. #
  5. # You don't have to use idf.py, you can use cmake directly
  6. # (or use cmake in an IDE)
  7. #
  8. #
  9. #
  10. # Copyright 2019 Espressif Systems (Shanghai) PTE LTD
  11. #
  12. # Licensed under the Apache License, Version 2.0 (the "License");
  13. # you may not use this file except in compliance with the License.
  14. # You may obtain a copy of the License at
  15. #
  16. # http://www.apache.org/licenses/LICENSE-2.0
  17. #
  18. # Unless required by applicable law or agreed to in writing, software
  19. # distributed under the License is distributed on an "AS IS" BASIS,
  20. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. # See the License for the specific language governing permissions and
  22. # limitations under the License.
  23. #
  24. # WARNING: we don't check for Python build-time dependencies until
  25. # check_environment() function below. If possible, avoid importing
  26. # any external libraries here - put in external script, or import in
  27. # their specific function instead.
  28. import codecs
  29. import json
  30. import locale
  31. import multiprocessing
  32. import os
  33. import os.path
  34. import re
  35. import shutil
  36. import subprocess
  37. import sys
  38. class FatalError(RuntimeError):
  39. """
  40. Wrapper class for runtime errors that aren't caused by bugs in idf.py or the build proces.s
  41. """
  42. pass
  43. # Use this Python interpreter for any subprocesses we launch
  44. PYTHON = sys.executable
  45. # note: os.environ changes don't automatically propagate to child processes,
  46. # you have to pass env=os.environ explicitly anywhere that we create a process
  47. os.environ["PYTHON"] = sys.executable
  48. # Name of the program, normally 'idf.py'.
  49. # Can be overridden from idf.bat using IDF_PY_PROGRAM_NAME
  50. PROG = os.getenv("IDF_PY_PROGRAM_NAME", sys.argv[0])
  51. # Make flavors, across the various kinds of Windows environments & POSIX...
  52. if "MSYSTEM" in os.environ: # MSYS
  53. MAKE_CMD = "make"
  54. MAKE_GENERATOR = "MSYS Makefiles"
  55. elif os.name == "nt": # other Windows
  56. MAKE_CMD = "mingw32-make"
  57. MAKE_GENERATOR = "MinGW Makefiles"
  58. else:
  59. MAKE_CMD = "make"
  60. MAKE_GENERATOR = "Unix Makefiles"
  61. GENERATORS = [
  62. # ('generator name', 'build command line', 'version command line', 'verbose flag')
  63. ("Ninja", ["ninja"], ["ninja", "--version"], "-v"),
  64. (
  65. MAKE_GENERATOR,
  66. [MAKE_CMD, "-j", str(multiprocessing.cpu_count() + 2)],
  67. [MAKE_CMD, "--version"],
  68. "VERBOSE=1",
  69. ),
  70. ]
  71. GENERATOR_CMDS = dict((a[0], a[1]) for a in GENERATORS)
  72. GENERATOR_VERBOSE = dict((a[0], a[3]) for a in GENERATORS)
  73. def _run_tool(tool_name, args, cwd):
  74. def quote_arg(arg):
  75. " Quote 'arg' if necessary "
  76. if " " in arg and not (arg.startswith('"') or arg.startswith("'")):
  77. return "'" + arg + "'"
  78. return arg
  79. display_args = " ".join(quote_arg(arg) for arg in args)
  80. print("Running %s in directory %s" % (tool_name, quote_arg(cwd)))
  81. print('Executing "%s"...' % str(display_args))
  82. try:
  83. # Note: we explicitly pass in os.environ here, as we may have set IDF_PATH there during startup
  84. subprocess.check_call(args, env=os.environ, cwd=cwd)
  85. except subprocess.CalledProcessError as e:
  86. raise FatalError("%s failed with exit code %d" % (tool_name, e.returncode))
  87. def _realpath(path):
  88. """
  89. Return the cannonical path with normalized case.
  90. It is useful on Windows to comparision paths in case-insensitive manner.
  91. On Unix and Mac OS X it works as `os.path.realpath()` only.
  92. """
  93. return os.path.normcase(os.path.realpath(path))
  94. def check_environment():
  95. """
  96. Verify the environment contains the top-level tools we need to operate
  97. (cmake will check a lot of other things)
  98. """
  99. if not executable_exists(["cmake", "--version"]):
  100. raise FatalError("'cmake' must be available on the PATH to use %s" % PROG)
  101. # find the directory idf.py is in, then the parent directory of this, and assume this is IDF_PATH
  102. detected_idf_path = _realpath(os.path.join(os.path.dirname(__file__), ".."))
  103. if "IDF_PATH" in os.environ:
  104. set_idf_path = _realpath(os.environ["IDF_PATH"])
  105. if set_idf_path != detected_idf_path:
  106. print(
  107. "WARNING: IDF_PATH environment variable is set to %s but %s path indicates IDF directory %s. "
  108. "Using the environment variable directory, but results may be unexpected..."
  109. % (set_idf_path, PROG, detected_idf_path)
  110. )
  111. else:
  112. print("Setting IDF_PATH environment variable: %s" % detected_idf_path)
  113. os.environ["IDF_PATH"] = detected_idf_path
  114. # check Python dependencies
  115. print("Checking Python dependencies...")
  116. try:
  117. subprocess.check_call(
  118. [
  119. os.environ["PYTHON"],
  120. os.path.join(
  121. os.environ["IDF_PATH"], "tools", "check_python_dependencies.py"
  122. ),
  123. ],
  124. env=os.environ,
  125. )
  126. except subprocess.CalledProcessError:
  127. raise SystemExit(1)
  128. def executable_exists(args):
  129. try:
  130. subprocess.check_output(args)
  131. return True
  132. except Exception:
  133. return False
  134. def detect_cmake_generator():
  135. """
  136. Find the default cmake generator, if none was specified. Raises an exception if no valid generator is found.
  137. """
  138. for (generator, _, version_check, _) in GENERATORS:
  139. if executable_exists(version_check):
  140. return generator
  141. raise FatalError(
  142. "To use %s, either the 'ninja' or 'GNU make' build tool must be available in the PATH"
  143. % PROG
  144. )
  145. def _strip_quotes(value, regexp=re.compile(r"^\"(.*)\"$|^'(.*)'$|^(.*)$")):
  146. """
  147. Strip quotes like CMake does during parsing cache entries
  148. """
  149. return [x for x in regexp.match(value).groups() if x is not None][0].rstrip()
  150. def _new_cmakecache_entries(cache_path, new_cache_entries):
  151. if not os.path.exists(cache_path):
  152. return True
  153. if new_cache_entries:
  154. current_cache = parse_cmakecache(cache_path)
  155. for entry in new_cache_entries:
  156. key, value = entry.split("=", 1)
  157. current_value = current_cache.get(key, None)
  158. if current_value is None or _strip_quotes(value) != current_value:
  159. return True
  160. return False
  161. def _ensure_build_directory(args, always_run_cmake=False):
  162. """Check the build directory exists and that cmake has been run there.
  163. If this isn't the case, create the build directory (if necessary) and
  164. do an initial cmake run to configure it.
  165. This function will also check args.generator parameter. If the parameter is incompatible with
  166. the build directory, an error is raised. If the parameter is None, this function will set it to
  167. an auto-detected default generator or to the value already configured in the build directory.
  168. """
  169. project_dir = args.project_dir
  170. # Verify the project directory
  171. if not os.path.isdir(project_dir):
  172. if not os.path.exists(project_dir):
  173. raise FatalError("Project directory %s does not exist" % project_dir)
  174. else:
  175. raise FatalError("%s must be a project directory" % project_dir)
  176. if not os.path.exists(os.path.join(project_dir, "CMakeLists.txt")):
  177. raise FatalError(
  178. "CMakeLists.txt not found in project directory %s" % project_dir
  179. )
  180. # Verify/create the build directory
  181. build_dir = args.build_dir
  182. if not os.path.isdir(build_dir):
  183. os.makedirs(build_dir)
  184. cache_path = os.path.join(build_dir, "CMakeCache.txt")
  185. args.define_cache_entry = list(args.define_cache_entry)
  186. args.define_cache_entry.append("CCACHE_ENABLE=%d" % args.ccache)
  187. if always_run_cmake or _new_cmakecache_entries(cache_path, args.define_cache_entry):
  188. if args.generator is None:
  189. args.generator = detect_cmake_generator()
  190. try:
  191. cmake_args = [
  192. "cmake",
  193. "-G",
  194. args.generator,
  195. "-DPYTHON_DEPS_CHECKED=1",
  196. "-DESP_PLATFORM=1",
  197. ]
  198. if not args.no_warnings:
  199. cmake_args += ["--warn-uninitialized"]
  200. cmake_args += ["-DWARN_UNINITIALIZED=1"]
  201. if args.define_cache_entry:
  202. cmake_args += ["-D" + d for d in args.define_cache_entry]
  203. cmake_args += [project_dir]
  204. _run_tool("cmake", cmake_args, cwd=args.build_dir)
  205. except Exception:
  206. # don't allow partially valid CMakeCache.txt files,
  207. # to keep the "should I run cmake?" logic simple
  208. if os.path.exists(cache_path):
  209. os.remove(cache_path)
  210. raise
  211. # Learn some things from the CMakeCache.txt file in the build directory
  212. cache = parse_cmakecache(cache_path)
  213. try:
  214. generator = cache["CMAKE_GENERATOR"]
  215. except KeyError:
  216. generator = detect_cmake_generator()
  217. if args.generator is None:
  218. args.generator = (
  219. generator
  220. ) # reuse the previously configured generator, if none was given
  221. if generator != args.generator:
  222. raise FatalError(
  223. "Build is configured for generator '%s' not '%s'. Run '%s fullclean' to start again."
  224. % (generator, args.generator, PROG)
  225. )
  226. try:
  227. home_dir = cache["CMAKE_HOME_DIRECTORY"]
  228. if _realpath(home_dir) != _realpath(project_dir):
  229. raise FatalError(
  230. "Build directory '%s' configured for project '%s' not '%s'. Run '%s fullclean' to start again."
  231. % (build_dir, _realpath(home_dir), _realpath(project_dir), PROG)
  232. )
  233. except KeyError:
  234. pass # if cmake failed part way, CMAKE_HOME_DIRECTORY may not be set yet
  235. def parse_cmakecache(path):
  236. """
  237. Parse the CMakeCache file at 'path'.
  238. Returns a dict of name:value.
  239. CMakeCache entries also each have a "type", but this is currently ignored.
  240. """
  241. result = {}
  242. with open(path) as f:
  243. for line in f:
  244. # cmake cache lines look like: CMAKE_CXX_FLAGS_DEBUG:STRING=-g
  245. # groups are name, type, value
  246. m = re.match(r"^([^#/:=]+):([^:=]+)=(.*)\n$", line)
  247. if m:
  248. result[m.group(1)] = m.group(3)
  249. return result
  250. def build_target(target_name, ctx, args):
  251. """
  252. Execute the target build system to build target 'target_name'
  253. Calls _ensure_build_directory() which will run cmake to generate a build
  254. directory (with the specified generator) as needed.
  255. """
  256. _ensure_build_directory(args)
  257. generator_cmd = GENERATOR_CMDS[args.generator]
  258. if args.ccache:
  259. # Setting CCACHE_BASEDIR & CCACHE_NO_HASHDIR ensures that project paths aren't stored in the ccache entries
  260. # (this means ccache hits can be shared between different projects. It may mean that some debug information
  261. # will point to files in another project, if these files are perfect duplicates of each other.)
  262. #
  263. # It would be nicer to set these from cmake, but there's no cross-platform way to set build-time environment
  264. # os.environ["CCACHE_BASEDIR"] = args.build_dir
  265. # os.environ["CCACHE_NO_HASHDIR"] = "1"
  266. pass
  267. if args.verbose:
  268. generator_cmd += [GENERATOR_VERBOSE[args.generator]]
  269. _run_tool(generator_cmd[0], generator_cmd + [target_name], args.build_dir)
  270. def _get_esptool_args(args):
  271. esptool_path = os.path.join(
  272. os.environ["IDF_PATH"], "components/esptool_py/esptool/esptool.py"
  273. )
  274. if args.port is None:
  275. args.port = get_default_serial_port()
  276. result = [PYTHON, esptool_path]
  277. result += ["-p", args.port]
  278. result += ["-b", str(args.baud)]
  279. with open(os.path.join(args.build_dir, "flasher_args.json")) as f:
  280. flasher_args = json.load(f)
  281. extra_esptool_args = flasher_args["extra_esptool_args"]
  282. result += ["--before", extra_esptool_args["before"]]
  283. result += ["--after", extra_esptool_args["after"]]
  284. return result
  285. def flash(action, ctx, args):
  286. """
  287. Run esptool to flash the entire project, from an argfile generated by the build system
  288. """
  289. flasher_args_path = { # action -> name of flasher args file generated by build system
  290. "bootloader-flash": "flash_bootloader_args",
  291. "partition_table-flash": "flash_partition_table_args",
  292. "app-flash": "flash_app_args",
  293. "flash": "flash_project_args",
  294. "encrypted-app-flash": "flash_encrypted_app_args",
  295. "encrypted-flash": "flash_encrypted_project_args",
  296. }[
  297. action
  298. ]
  299. esptool_args = _get_esptool_args(args)
  300. esptool_args += ["write_flash", "@" + flasher_args_path]
  301. _run_tool("esptool.py", esptool_args, args.build_dir)
  302. def erase_flash(action, ctx, args):
  303. esptool_args = _get_esptool_args(args)
  304. esptool_args += ["erase_flash"]
  305. _run_tool("esptool.py", esptool_args, args.build_dir)
  306. def monitor(action, ctx, args, print_filter, monitor_baud):
  307. """
  308. Run idf_monitor.py to watch build output
  309. """
  310. if args.port is None:
  311. args.port = get_default_serial_port()
  312. desc_path = os.path.join(args.build_dir, "project_description.json")
  313. if not os.path.exists(desc_path):
  314. _ensure_build_directory(args)
  315. with open(desc_path, "r") as f:
  316. project_desc = json.load(f)
  317. elf_file = os.path.join(args.build_dir, project_desc["app_elf"])
  318. if not os.path.exists(elf_file):
  319. raise FatalError(
  320. "ELF file '%s' not found. You need to build & flash the project before running 'monitor', "
  321. "and the binary on the device must match the one in the build directory exactly. "
  322. "Try '%s flash monitor'." % (elf_file, PROG)
  323. )
  324. idf_monitor = os.path.join(os.environ["IDF_PATH"], "tools/idf_monitor.py")
  325. monitor_args = [PYTHON, idf_monitor]
  326. if args.port is not None:
  327. monitor_args += ["-p", args.port]
  328. if not monitor_baud:
  329. if os.getenv("IDF_MONITOR_BAUD"):
  330. monitor_baud = os.getenv("IDF_MONITOR_BAUD", None)
  331. elif os.getenv("MONITORBAUD"):
  332. monitor_baud = os.getenv("MONITORBAUD", None)
  333. else:
  334. monitor_baud = project_desc["monitor_baud"]
  335. monitor_args += ["-b", monitor_baud]
  336. if print_filter is not None:
  337. monitor_args += ["--print_filter", print_filter]
  338. monitor_args += [elf_file]
  339. idf_py = [PYTHON] + get_commandline_options(ctx) # commands to re-run idf.py
  340. monitor_args += ["-m", " ".join("'%s'" % a for a in idf_py)]
  341. if "MSYSTEM" in os.environ:
  342. monitor_args = ["winpty"] + monitor_args
  343. _run_tool("idf_monitor", monitor_args, args.project_dir)
  344. def clean(action, ctx, args):
  345. if not os.path.isdir(args.build_dir):
  346. print("Build directory '%s' not found. Nothing to clean." % args.build_dir)
  347. return
  348. build_target("clean", ctx, args)
  349. def reconfigure(action, ctx, args):
  350. _ensure_build_directory(args, True)
  351. def _delete_windows_symlinks(directory):
  352. """
  353. It deletes symlinks recursively on Windows. It is useful for Python 2 which doesn't detect symlinks on Windows.
  354. """
  355. deleted_paths = []
  356. if os.name == "nt":
  357. import ctypes
  358. for root, dirnames, _filenames in os.walk(directory):
  359. for d in dirnames:
  360. full_path = os.path.join(root, d)
  361. try:
  362. full_path = full_path.decode("utf-8")
  363. except Exception:
  364. pass
  365. if ctypes.windll.kernel32.GetFileAttributesW(full_path) & 0x0400:
  366. os.rmdir(full_path)
  367. deleted_paths.append(full_path)
  368. return deleted_paths
  369. def fullclean(action, ctx, args):
  370. build_dir = args.build_dir
  371. if not os.path.isdir(build_dir):
  372. print("Build directory '%s' not found. Nothing to clean." % build_dir)
  373. return
  374. if len(os.listdir(build_dir)) == 0:
  375. print("Build directory '%s' is empty. Nothing to clean." % build_dir)
  376. return
  377. if not os.path.exists(os.path.join(build_dir, "CMakeCache.txt")):
  378. raise FatalError(
  379. "Directory '%s' doesn't seem to be a CMake build directory. Refusing to automatically "
  380. "delete files in this directory. Delete the directory manually to 'clean' it."
  381. % build_dir
  382. )
  383. red_flags = ["CMakeLists.txt", ".git", ".svn"]
  384. for red in red_flags:
  385. red = os.path.join(build_dir, red)
  386. if os.path.exists(red):
  387. raise FatalError(
  388. "Refusing to automatically delete files in directory containing '%s'. Delete files manually if you're sure."
  389. % red
  390. )
  391. # OK, delete everything in the build directory...
  392. # Note: Python 2.7 doesn't detect symlinks on Windows (it is supported form 3.2). Tools promising to not
  393. # follow symlinks will actually follow them. Deleting the build directory with symlinks deletes also items
  394. # outside of this directory.
  395. deleted_symlinks = _delete_windows_symlinks(build_dir)
  396. if args.verbose and len(deleted_symlinks) > 1:
  397. print(
  398. "The following symlinks were identified and removed:\n%s"
  399. % "\n".join(deleted_symlinks)
  400. )
  401. for f in os.listdir(
  402. build_dir
  403. ): # TODO: once we are Python 3 only, this can be os.scandir()
  404. f = os.path.join(build_dir, f)
  405. if args.verbose:
  406. print("Removing: %s" % f)
  407. if os.path.isdir(f):
  408. shutil.rmtree(f)
  409. else:
  410. os.remove(f)
  411. def _safe_relpath(path, start=None):
  412. """ Return a relative path, same as os.path.relpath, but only if this is possible.
  413. It is not possible on Windows, if the start directory and the path are on different drives.
  414. """
  415. try:
  416. return os.path.relpath(path, os.curdir if start is None else start)
  417. except ValueError:
  418. return os.path.abspath(path)
  419. def get_commandline_options(ctx):
  420. """ Return all the command line options up to first action """
  421. # This approach ignores argument parsing done Click
  422. result = []
  423. for arg in sys.argv:
  424. if arg in ctx.command.commands_with_aliases:
  425. break
  426. result.append(arg)
  427. return result
  428. def get_default_serial_port():
  429. """ Return a default serial port. esptool can do this (smarter), but it can create
  430. inconsistencies where esptool.py uses one port and idf_monitor uses another.
  431. Same logic as esptool.py search order, reverse sort by name and choose the first port.
  432. """
  433. # Import is done here in order to move it after the check_environment() ensured that pyserial has been installed
  434. import serial.tools.list_ports
  435. ports = list(reversed(sorted(p.device for p in serial.tools.list_ports.comports())))
  436. try:
  437. print(
  438. "Choosing default port %s (use '-p PORT' option to set a specific serial port)"
  439. % ports[0].encode("ascii", "ignore")
  440. )
  441. return ports[0]
  442. except IndexError:
  443. raise RuntimeError(
  444. "No serial ports found. Connect a device, or use '-p PORT' option to set a specific port."
  445. )
  446. class PropertyDict(dict):
  447. def __getattr__(self, name):
  448. if name in self:
  449. return self[name]
  450. else:
  451. raise AttributeError("'PropertyDict' object has no attribute '%s'" % name)
  452. def __setattr__(self, name, value):
  453. self[name] = value
  454. def __delattr__(self, name):
  455. if name in self:
  456. del self[name]
  457. else:
  458. raise AttributeError("'PropertyDict' object has no attribute '%s'" % name)
  459. def init_cli():
  460. # Click is imported here to run it after check_environment()
  461. import click
  462. class Task(object):
  463. def __init__(
  464. self, callback, name, aliases, dependencies, order_dependencies, action_args
  465. ):
  466. self.callback = callback
  467. self.name = name
  468. self.dependencies = dependencies
  469. self.order_dependencies = order_dependencies
  470. self.action_args = action_args
  471. self.aliases = aliases
  472. def run(self, context, global_args, action_args=None):
  473. if action_args is None:
  474. action_args = self.action_args
  475. self.callback(self.name, context, global_args, **action_args)
  476. class Action(click.Command):
  477. def __init__(
  478. self,
  479. name=None,
  480. aliases=None,
  481. dependencies=None,
  482. order_dependencies=None,
  483. **kwargs
  484. ):
  485. super(Action, self).__init__(name, **kwargs)
  486. self.name = self.name or self.callback.__name__
  487. if aliases is None:
  488. aliases = []
  489. self.aliases = aliases
  490. self.help = self.help or self.callback.__doc__
  491. if self.help is None:
  492. self.help = ""
  493. if dependencies is None:
  494. dependencies = []
  495. if order_dependencies is None:
  496. order_dependencies = []
  497. # Show first line of help if short help is missing
  498. self.short_help = self.short_help or self.help.split("\n")[0]
  499. # Add aliases to help string
  500. if aliases:
  501. aliases_help = "Aliases: %s." % ", ".join(aliases)
  502. self.help = "\n".join([self.help, aliases_help])
  503. self.short_help = " ".join([aliases_help, self.short_help])
  504. if self.callback is not None:
  505. callback = self.callback
  506. def wrapped_callback(**action_args):
  507. return Task(
  508. callback=callback,
  509. name=self.name,
  510. dependencies=dependencies,
  511. order_dependencies=order_dependencies,
  512. action_args=action_args,
  513. aliases=self.aliases,
  514. )
  515. self.callback = wrapped_callback
  516. class Argument(click.Argument):
  517. """Positional argument"""
  518. def __init__(self, **kwargs):
  519. names = kwargs.pop("names")
  520. super(Argument, self).__init__(names, **kwargs)
  521. class Scope(object):
  522. """
  523. Scope for sub-command option.
  524. possible values:
  525. - default - only available on defined level (global/action)
  526. - global - When defined for action, also available as global
  527. - shared - Opposite to 'global': when defined in global scope, also available for all actions
  528. """
  529. SCOPES = ("default", "global", "shared")
  530. def __init__(self, scope=None):
  531. if scope is None:
  532. self._scope = "default"
  533. elif isinstance(scope, str) and scope in self.SCOPES:
  534. self._scope = scope
  535. elif isinstance(scope, Scope):
  536. self._scope = str(scope)
  537. else:
  538. raise FatalError("Unknown scope for option: %s" % scope)
  539. @property
  540. def is_global(self):
  541. return self._scope == "global"
  542. @property
  543. def is_shared(self):
  544. return self._scope == "shared"
  545. def __str__(self):
  546. return self._scope
  547. class Option(click.Option):
  548. """Option that knows whether it should be global"""
  549. def __init__(self, scope=None, **kwargs):
  550. kwargs["param_decls"] = kwargs.pop("names")
  551. super(Option, self).__init__(**kwargs)
  552. self.scope = Scope(scope)
  553. if self.scope.is_global:
  554. self.help += " This option can be used at most once either globally, or for one subcommand."
  555. class CLI(click.MultiCommand):
  556. """Action list contains all actions with options available for CLI"""
  557. def __init__(self, action_lists=None, help=None):
  558. super(CLI, self).__init__(
  559. chain=True,
  560. invoke_without_command=True,
  561. result_callback=self.execute_tasks,
  562. context_settings={"max_content_width": 140},
  563. help=help,
  564. )
  565. self._actions = {}
  566. self.global_action_callbacks = []
  567. self.commands_with_aliases = {}
  568. if action_lists is None:
  569. action_lists = []
  570. shared_options = []
  571. for action_list in action_lists:
  572. # Global options
  573. for option_args in action_list.get("global_options", []):
  574. option = Option(**option_args)
  575. self.params.append(option)
  576. if option.scope.is_shared:
  577. shared_options.append(option)
  578. for action_list in action_lists:
  579. # Global options validators
  580. self.global_action_callbacks.extend(
  581. action_list.get("global_action_callbacks", [])
  582. )
  583. for action_list in action_lists:
  584. # Actions
  585. for name, action in action_list.get("actions", {}).items():
  586. arguments = action.pop("arguments", [])
  587. options = action.pop("options", [])
  588. if arguments is None:
  589. arguments = []
  590. if options is None:
  591. options = []
  592. self._actions[name] = Action(name=name, **action)
  593. for alias in [name] + action.get("aliases", []):
  594. self.commands_with_aliases[alias] = name
  595. for argument_args in arguments:
  596. self._actions[name].params.append(Argument(**argument_args))
  597. # Add all shared options
  598. for option in shared_options:
  599. self._actions[name].params.append(option)
  600. for option_args in options:
  601. option = Option(**option_args)
  602. if option.scope.is_shared:
  603. raise FatalError(
  604. '"%s" is defined for action "%s". '
  605. ' "shared" options can be declared only on global level' % (option.name, name)
  606. )
  607. # Promote options to global if see for the first time
  608. if option.scope.is_global and option.name not in [o.name for o in self.params]:
  609. self.params.append(option)
  610. self._actions[name].params.append(option)
  611. def list_commands(self, ctx):
  612. return sorted(self._actions)
  613. def get_command(self, ctx, name):
  614. return self._actions.get(self.commands_with_aliases.get(name))
  615. def _print_closing_message(self, args, actions):
  616. # print a closing message of some kind
  617. #
  618. if "flash" in str(actions):
  619. print("Done")
  620. return
  621. # Otherwise, if we built any binaries print a message about
  622. # how to flash them
  623. def print_flashing_message(title, key):
  624. print("\n%s build complete. To flash, run this command:" % title)
  625. with open(os.path.join(args.build_dir, "flasher_args.json")) as f:
  626. flasher_args = json.load(f)
  627. def flasher_path(f):
  628. return _safe_relpath(os.path.join(args.build_dir, f))
  629. if key != "project": # flashing a single item
  630. cmd = ""
  631. if (
  632. key == "bootloader"
  633. ): # bootloader needs --flash-mode, etc to be passed in
  634. cmd = " ".join(flasher_args["write_flash_args"]) + " "
  635. cmd += flasher_args[key]["offset"] + " "
  636. cmd += flasher_path(flasher_args[key]["file"])
  637. else: # flashing the whole project
  638. cmd = " ".join(flasher_args["write_flash_args"]) + " "
  639. flash_items = sorted(
  640. (
  641. (o, f)
  642. for (o, f) in flasher_args["flash_files"].items()
  643. if len(o) > 0
  644. ),
  645. key=lambda x: int(x[0], 0),
  646. )
  647. for o, f in flash_items:
  648. cmd += o + " " + flasher_path(f) + " "
  649. print("%s %s -p %s -b %s --before %s --after %s write_flash %s" % (
  650. PYTHON,
  651. _safe_relpath("%s/components/esptool_py/esptool/esptool.py" % os.environ["IDF_PATH"]),
  652. args.port or "(PORT)",
  653. args.baud,
  654. flasher_args["extra_esptool_args"]["before"],
  655. flasher_args["extra_esptool_args"]["after"],
  656. cmd.strip(),
  657. ))
  658. print("or run 'idf.py -p %s %s'" % (
  659. args.port or "(PORT)",
  660. key + "-flash" if key != "project" else "flash",
  661. ))
  662. if "all" in actions or "build" in actions:
  663. print_flashing_message("Project", "project")
  664. else:
  665. if "app" in actions:
  666. print_flashing_message("App", "app")
  667. if "partition_table" in actions:
  668. print_flashing_message("Partition Table", "partition_table")
  669. if "bootloader" in actions:
  670. print_flashing_message("Bootloader", "bootloader")
  671. def execute_tasks(self, tasks, **kwargs):
  672. ctx = click.get_current_context()
  673. global_args = PropertyDict(ctx.params)
  674. # Set propagated global options
  675. for task in tasks:
  676. for key in list(task.action_args):
  677. option = next((o for o in ctx.command.params if o.name == key), None)
  678. if option and (option.scope.is_global or option.scope.is_shared):
  679. local_value = task.action_args.pop(key)
  680. global_value = global_args[key]
  681. default = () if option.multiple else option.default
  682. if global_value != default and local_value != default and global_value != local_value:
  683. raise FatalError(
  684. 'Option "%s" provided for "%s" is already defined to a different value. '
  685. "This option can appear at most once in the command line." % (key, task.name)
  686. )
  687. if local_value != default:
  688. global_args[key] = local_value
  689. # Validate global arguments
  690. for action_callback in ctx.command.global_action_callbacks:
  691. action_callback(ctx, global_args, tasks)
  692. # very simple dependency management
  693. completed_tasks = set()
  694. if not tasks:
  695. print(ctx.get_help())
  696. ctx.exit()
  697. while tasks:
  698. task = tasks[0]
  699. tasks_dict = dict([(t.name, t) for t in tasks])
  700. name_with_aliases = task.name
  701. if task.aliases:
  702. name_with_aliases += " (aliases: %s)" % ", ".join(task.aliases)
  703. ready_to_run = True
  704. for dep in task.dependencies:
  705. if dep not in completed_tasks:
  706. print(
  707. 'Adding %s\'s dependency "%s" to list of actions'
  708. % (task.name, dep)
  709. )
  710. dep_task = ctx.invoke(ctx.command.get_command(ctx, dep))
  711. # Remove global options from dependent tasks
  712. for key in list(dep_task.action_args):
  713. option = next((o for o in ctx.command.params if o.name == key), None)
  714. if option and (option.scope.is_global or option.scope.is_shared):
  715. dep_task.action_args.pop(key)
  716. tasks.insert(0, dep_task)
  717. ready_to_run = False
  718. for dep in task.order_dependencies:
  719. if dep in tasks_dict.keys() and dep not in completed_tasks:
  720. tasks.insert(0, tasks.pop(tasks.index(tasks_dict[dep])))
  721. ready_to_run = False
  722. if ready_to_run:
  723. tasks.pop(0)
  724. if task.name in completed_tasks:
  725. print(
  726. "Skipping action that is already done: %s"
  727. % name_with_aliases
  728. )
  729. else:
  730. print("Executing action: %s" % name_with_aliases)
  731. task.run(ctx, global_args, task.action_args)
  732. completed_tasks.add(task.name)
  733. self._print_closing_message(global_args, completed_tasks)
  734. @staticmethod
  735. def merge_action_lists(*action_lists):
  736. merged_actions = {
  737. "global_options": [],
  738. "actions": {},
  739. "global_action_callbacks": [],
  740. }
  741. for action_list in action_lists:
  742. merged_actions["global_options"].extend(
  743. action_list.get("global_options", [])
  744. )
  745. merged_actions["actions"].update(action_list.get("actions", {}))
  746. merged_actions["global_action_callbacks"].extend(
  747. action_list.get("global_action_callbacks", [])
  748. )
  749. return merged_actions
  750. # That's a tiny parser that parse project-dir even before constructing
  751. # fully featured click parser to be sure that extensions are loaded from the right place
  752. @click.command(
  753. add_help_option=False,
  754. context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
  755. )
  756. @click.option("-C", "--project-dir", default=os.getcwd())
  757. def parse_project_dir(project_dir):
  758. return _realpath(project_dir)
  759. project_dir = parse_project_dir(standalone_mode=False)
  760. # Load base idf commands
  761. def validate_root_options(ctx, args, tasks):
  762. args.project_dir = _realpath(args.project_dir)
  763. if args.build_dir is not None and args.project_dir == _realpath(args.build_dir):
  764. raise FatalError(
  765. "Setting the build directory to the project directory is not supported. Suggest dropping "
  766. "--build-dir option, the default is a 'build' subdirectory inside the project directory."
  767. )
  768. if args.build_dir is None:
  769. args.build_dir = os.path.join(args.project_dir, "build")
  770. args.build_dir = _realpath(args.build_dir)
  771. # Possible keys for action dict are: global_options, actions and global_action_callbacks
  772. global_options = [
  773. {
  774. "names": ["-D", "--define-cache-entry"],
  775. "help": "Create a cmake cache entry.",
  776. "scope": "global",
  777. "multiple": True,
  778. }
  779. ]
  780. root_options = {
  781. "global_options": [
  782. {
  783. "names": ["-C", "--project-dir"],
  784. "help": "Project directory.",
  785. "type": click.Path(),
  786. "default": os.getcwd(),
  787. },
  788. {
  789. "names": ["-B", "--build-dir"],
  790. "help": "Build directory.",
  791. "type": click.Path(),
  792. "default": None,
  793. },
  794. {
  795. "names": ["-n", "--no-warnings"],
  796. "help": "Disable Cmake warnings.",
  797. "is_flag": True,
  798. "default": False,
  799. },
  800. {
  801. "names": ["-v", "--verbose"],
  802. "help": "Verbose build output.",
  803. "is_flag": True,
  804. "default": False,
  805. },
  806. {
  807. "names": ["--ccache/--no-ccache"],
  808. "help": "Use ccache in build. Disabled by default, unless IDF_CCACHE_ENABLE environment variable is set to a non-zero value.",
  809. "is_flag": True,
  810. "default": os.getenv("IDF_CCACHE_ENABLE") not in [None, "", "0"],
  811. },
  812. {
  813. "names": ["-G", "--generator"],
  814. "help": "CMake generator.",
  815. "type": click.Choice(GENERATOR_CMDS.keys()),
  816. },
  817. ],
  818. "global_action_callbacks": [validate_root_options],
  819. }
  820. build_actions = {
  821. "actions": {
  822. "all": {
  823. "aliases": ["build"],
  824. "callback": build_target,
  825. "short_help": "Build the project.",
  826. "help": "Build the project. This can involve multiple steps:\n\n"
  827. + "1. Create the build directory if needed. The sub-directory 'build' is used to hold build output, "
  828. + "although this can be changed with the -B option.\n\n"
  829. + "2. Run CMake as necessary to configure the project and generate build files for the main build tool.\n\n"
  830. + "3. Run the main build tool (Ninja or GNU Make). By default, the build tool is automatically detected "
  831. + "but it can be explicitly set by passing the -G option to idf.py.\n\n",
  832. "options": global_options,
  833. "order_dependencies": [
  834. "reconfigure",
  835. "menuconfig",
  836. "clean",
  837. "fullclean",
  838. ],
  839. },
  840. "menuconfig": {
  841. "callback": build_target,
  842. "help": 'Run "menuconfig" project configuration tool.',
  843. "options": global_options,
  844. },
  845. "confserver": {
  846. "callback": build_target,
  847. "help": "Run JSON configuration server.",
  848. "options": global_options,
  849. },
  850. "size": {
  851. "callback": build_target,
  852. "help": "Print basic size information about the app.",
  853. "options": global_options,
  854. "dependencies": ["app"],
  855. },
  856. "size-components": {
  857. "callback": build_target,
  858. "help": "Print per-component size information.",
  859. "options": global_options,
  860. "dependencies": ["app"],
  861. },
  862. "size-files": {
  863. "callback": build_target,
  864. "help": "Print per-source-file size information.",
  865. "options": global_options,
  866. "dependencies": ["app"],
  867. },
  868. "bootloader": {
  869. "callback": build_target,
  870. "help": "Build only bootloader.",
  871. "options": global_options,
  872. },
  873. "app": {
  874. "callback": build_target,
  875. "help": "Build only the app.",
  876. "order_dependencies": ["clean", "fullclean", "reconfigure"],
  877. "options": global_options,
  878. },
  879. "efuse_common_table": {
  880. "callback": build_target,
  881. "help": "Genereate C-source for IDF's eFuse fields.",
  882. "order_dependencies": ["reconfigure"],
  883. "options": global_options,
  884. },
  885. "efuse_custom_table": {
  886. "callback": build_target,
  887. "help": "Genereate C-source for user's eFuse fields.",
  888. "order_dependencies": ["reconfigure"],
  889. "options": global_options,
  890. },
  891. "show_efuse_table": {
  892. "callback": build_target,
  893. "help": "Print eFuse table.",
  894. "order_dependencies": ["reconfigure"],
  895. "options": global_options,
  896. },
  897. "partition_table": {
  898. "callback": build_target,
  899. "help": "Build only partition table.",
  900. "order_dependencies": ["reconfigure"],
  901. "options": global_options,
  902. },
  903. "erase_otadata": {
  904. "callback": build_target,
  905. "help": "Erase otadata partition.",
  906. "options": global_options,
  907. },
  908. "read_otadata": {
  909. "callback": build_target,
  910. "help": "Read otadata partition.",
  911. "options": global_options,
  912. },
  913. }
  914. }
  915. clean_actions = {
  916. "actions": {
  917. "reconfigure": {
  918. "callback": reconfigure,
  919. "short_help": "Re-run CMake.",
  920. "help": "Re-run CMake even if it doesn't seem to need re-running. This isn't necessary during normal usage, "
  921. + "but can be useful after adding/removing files from the source tree, or when modifying CMake cache variables. "
  922. + "For example, \"idf.py -DNAME='VALUE' reconfigure\" "
  923. + 'can be used to set variable "NAME" in CMake cache to value "VALUE".',
  924. "options": global_options,
  925. "order_dependencies": ["menuconfig"],
  926. },
  927. "clean": {
  928. "callback": clean,
  929. "short_help": "Delete build output files from the build directory.",
  930. "help": "Delete build output files from the build directory , forcing a 'full rebuild' the next time "
  931. + "the project is built. Cleaning doesn't delete CMake configuration output and some other files",
  932. "order_dependencies": ["fullclean"],
  933. },
  934. "fullclean": {
  935. "callback": fullclean,
  936. "short_help": "Delete the entire build directory contents.",
  937. "help": "Delete the entire build directory contents. This includes all CMake configuration output."
  938. + "The next time the project is built, CMake will configure it from scratch. "
  939. + "Note that this option recursively deletes all files in the build directory, so use with care."
  940. + "Project configuration is not deleted.",
  941. },
  942. }
  943. }
  944. baud_rate = {
  945. "names": ["-b", "--baud"],
  946. "help": "Baud rate for flashing.",
  947. "scope": "global",
  948. "envvar": "ESPBAUD",
  949. "default": 460800,
  950. }
  951. port = {
  952. "names": ["-p", "--port"],
  953. "help": "Serial port.",
  954. "scope": "global",
  955. "envvar": "ESPPORT",
  956. "default": None,
  957. }
  958. serial_actions = {
  959. "actions": {
  960. "flash": {
  961. "callback": flash,
  962. "help": "Flash the project.",
  963. "options": global_options + [baud_rate, port],
  964. "dependencies": ["all"],
  965. "order_dependencies": ["erase_flash"],
  966. },
  967. "erase_flash": {
  968. "callback": erase_flash,
  969. "help": "Erase entire flash chip.",
  970. "options": [baud_rate, port],
  971. },
  972. "monitor": {
  973. "callback": monitor,
  974. "help": "Display serial output.",
  975. "options": [
  976. port, {
  977. "names": ["--print-filter", "--print_filter"],
  978. "help":
  979. ("Filter monitor output.\n"
  980. "Restrictions on what to print can be specified as a series of <tag>:<log_level> items "
  981. "where <tag> is the tag string and <log_level> is a character from the set "
  982. "{N, E, W, I, D, V, *} referring to a level. "
  983. 'For example, "tag1:W" matches and prints only the outputs written with '
  984. 'ESP_LOGW("tag1", ...) or at lower verbosity level, i.e. ESP_LOGE("tag1", ...). '
  985. 'Not specifying a <log_level> or using "*" defaults to Verbose level.\n'
  986. 'Please see the IDF Monitor section of the ESP-IDF documentation '
  987. 'for a more detailed description and further examples.'),
  988. "default":
  989. None,
  990. }, {
  991. "names": ["--monitor-baud", "-B"],
  992. "type":
  993. click.INT,
  994. "help": ("Baud rate for monitor.\n"
  995. "If this option is not provided IDF_MONITOR_BAUD and MONITORBAUD "
  996. "environment variables and project_description.json in build directory "
  997. "(generated by CMake from project's sdkconfig) "
  998. "will be checked for default value."),
  999. }
  1000. ],
  1001. "order_dependencies": [
  1002. "flash",
  1003. "partition_table-flash",
  1004. "bootloader-flash",
  1005. "app-flash",
  1006. ],
  1007. },
  1008. "partition_table-flash": {
  1009. "callback": flash,
  1010. "help": "Flash partition table only.",
  1011. "options": [baud_rate, port],
  1012. "dependencies": ["partition_table"],
  1013. "order_dependencies": ["erase_flash"],
  1014. },
  1015. "bootloader-flash": {
  1016. "callback": flash,
  1017. "help": "Flash bootloader only.",
  1018. "options": [baud_rate, port],
  1019. "dependencies": ["bootloader"],
  1020. "order_dependencies": ["erase_flash"],
  1021. },
  1022. "app-flash": {
  1023. "callback": flash,
  1024. "help": "Flash the app only.",
  1025. "options": [baud_rate, port],
  1026. "dependencies": ["app"],
  1027. "order_dependencies": ["erase_flash"],
  1028. },
  1029. "encrypted-app-flash": {
  1030. "callback": flash,
  1031. "help": "Flash the encrypted app only.",
  1032. "dependencies": ["app"],
  1033. "order_dependencies": ["erase_flash"],
  1034. },
  1035. "encrypted-flash": {
  1036. "callback": flash,
  1037. "help": "Flash the encrypted project.",
  1038. "dependencies": ["all"],
  1039. "order_dependencies": ["erase_flash"],
  1040. },
  1041. },
  1042. }
  1043. base_actions = CLI.merge_action_lists(
  1044. root_options, build_actions, clean_actions, serial_actions
  1045. )
  1046. all_actions = [base_actions]
  1047. # Load extensions
  1048. if os.path.exists(os.path.join(project_dir, "idf_ext.py")):
  1049. sys.path.append(project_dir)
  1050. try:
  1051. from idf_ext import action_extensions
  1052. except ImportError:
  1053. print("Error importing extension file idf_ext.py. Skipping.")
  1054. print(
  1055. "Please make sure that it contains implementation (even if it's empty) of add_action_extensions"
  1056. )
  1057. # Add actions extensions
  1058. try:
  1059. all_actions.append(action_extensions(base_actions, project_dir))
  1060. except NameError:
  1061. pass
  1062. return CLI(help="ESP-IDF build management", action_lists=all_actions)
  1063. def main():
  1064. check_environment()
  1065. cli = init_cli()
  1066. cli(prog_name=PROG)
  1067. def _valid_unicode_config():
  1068. # Python 2 is always good
  1069. if sys.version_info[0] == 2:
  1070. return True
  1071. # With python 3 unicode environment is required
  1072. try:
  1073. return codecs.lookup(locale.getpreferredencoding()).name != "ascii"
  1074. except Exception:
  1075. return False
  1076. def _find_usable_locale():
  1077. try:
  1078. locales = subprocess.Popen(
  1079. ["locale", "-a"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
  1080. ).communicate()[0]
  1081. except OSError:
  1082. locales = ""
  1083. if isinstance(locales, bytes):
  1084. locales = locales.decode("ascii", "replace")
  1085. usable_locales = []
  1086. for line in locales.splitlines():
  1087. locale = line.strip()
  1088. locale_name = locale.lower().replace("-", "")
  1089. # C.UTF-8 is the best option, if supported
  1090. if locale_name == "c.utf8":
  1091. return locale
  1092. if locale_name.endswith(".utf8"):
  1093. # Make a preference of english locales
  1094. if locale.startswith("en_"):
  1095. usable_locales.insert(0, locale)
  1096. else:
  1097. usable_locales.append(locale)
  1098. if not usable_locales:
  1099. raise FatalError(
  1100. "Support for Unicode filenames is required, but no suitable UTF-8 locale was found on your system."
  1101. " Please refer to the manual for your operating system for details on locale reconfiguration."
  1102. )
  1103. return usable_locales[0]
  1104. if __name__ == "__main__":
  1105. try:
  1106. # On MSYS2 we need to run idf.py with "winpty" in order to be able to cancel the subprocesses properly on
  1107. # keyboard interrupt (CTRL+C).
  1108. # Using an own global variable for indicating that we are running with "winpty" seems to be the most suitable
  1109. # option as os.environment['_'] contains "winpty" only when it is run manually from console.
  1110. WINPTY_VAR = "WINPTY"
  1111. WINPTY_EXE = "winpty"
  1112. if ("MSYSTEM" in os.environ) and (
  1113. not os.environ.get("_", "").endswith(WINPTY_EXE) and WINPTY_VAR not in os.environ
  1114. ):
  1115. if 'menuconfig' in sys.argv:
  1116. # don't use winpty for menuconfig because it will print weird characters
  1117. main()
  1118. else:
  1119. os.environ[WINPTY_VAR] = "1" # the value is of no interest to us
  1120. # idf.py calls itself with "winpty" and WINPTY global variable set
  1121. ret = subprocess.call(
  1122. [WINPTY_EXE, sys.executable] + sys.argv, env=os.environ
  1123. )
  1124. if ret:
  1125. raise SystemExit(ret)
  1126. elif os.name == "posix" and not _valid_unicode_config():
  1127. # Trying to find best utf-8 locale available on the system and restart python with it
  1128. best_locale = _find_usable_locale()
  1129. print(
  1130. "Your environment is not configured to handle unicode filenames outside of ASCII range."
  1131. " Environment variable LC_ALL is temporary set to %s for unicode support."
  1132. % best_locale
  1133. )
  1134. os.environ["LC_ALL"] = best_locale
  1135. ret = subprocess.call([sys.executable] + sys.argv, env=os.environ)
  1136. if ret:
  1137. raise SystemExit(ret)
  1138. else:
  1139. main()
  1140. except FatalError as e:
  1141. print(e)
  1142. sys.exit(2)