2015-11-10 2 views
1

У меня возникла проблема с AddOption в SCons, где я указываю несколько флагов для одной опции. Он не поднимает один из флагов. В этом примере я хочу, чтобы оба -V и --verbose отключили ту же опцию, но она работает только для --verbose.SCons with AddOption не фиксирует все указанные флаги

Вот минимальный рабочий пример.

./SConstruct

AddOption("-V", "--verbose", 
      action="store_true", dest="verbose", default=False, 
      help="Print everything to stdout") 
if not GetOption('help'): 
    if GetOption('verbose'): 
     print '## VERBOSITORY IS ON ##' 
    else: 
     print '## VERBOSITORY IS OFF ##' 

Который при запуске мы получаем следующее ...

+ scons --help 
scons: Reading SConscript files ... 
scons: done reading SConscript files. 
usage: scons [OPTION] [TARGET] ... 

SCons Options: 
    -b, -d, -e, -m, -S, -t, -w, --environment-overrides, --no-keep-going, 
    --no-print-directory, --print-directory, --stop, --touch 
           Ignored for compatibility. 
    -c, --clean, --remove  Remove specified targets and dependencies. 
    -C DIR, --directory=DIR  Change to DIR before doing anything. 
    --cache-debug=FILE   Print CacheDir debug info to FILE. 
    --cache-disable, --no-cache 
           Do not retrieve built targets from CacheDir. 
    --cache-force, --cache-populate 
           Copy already-built targets into the CacheDir. 
    --cache-readonly   Do not update CacheDir with built targets. 
    --cache-show    Print build actions for files from CacheDir. 
    --config=MODE    Controls Configure subsystem: auto, force, 
           cache. 
    -D       Search up directory tree for SConstruct, 
           build all Default() targets. 
    --debug=TYPE    Print various types of debugging information: 
           count, duplicate, explain, findlibs, includes, 
           memoizer, memory, objects, pdb, prepare, 
           presub, stacktrace, time. 
    --diskcheck=TYPE   Enable specific on-disk checks. 
    --duplicate=DUPLICATE  Set the preferred duplication methods. Must be 
           one of hard-soft-copy, soft-hard-copy, 
           hard-copy, soft-copy, copy 
    -f FILE, --file=FILE, --makefile=FILE, --sconstruct=FILE 
           Read FILE as the top-level SConstruct file. 
    -h, --help     Print defined help message, or this one. 
    -H, --help-options   Print this message and exit. 
    -i, --ignore-errors   Ignore errors from build actions. 
    -I DIR, --include-dir=DIR Search DIR for imported Python modules. 
    --implicit-cache   Cache implicit dependencies 
    --implicit-deps-changed  Ignore cached implicit dependencies. 
    --implicit-deps-unchanged Ignore changes in implicit dependencies. 
    --interact, --interactive Run in interactive mode. 
    -j N, --jobs=N    Allow N jobs at once. 
    -k, --keep-going   Keep going when a target can't be made. 
    --max-drift=N    Set maximum system clock drift to N seconds. 
    --md5-chunksize=N   Set chunk-size for MD5 signature computation to 
           N kilobytes. 
    -n, --no-exec, --just-print, --dry-run, --recon 
           Don't build; just print commands. 
    --no-site-dir    Don't search or use the usual site_scons dir. 
    --profile=FILE    Profile SCons and put results in FILE. 
    -q, --question    Don't build; exit status says if up to date. 
    -Q       Suppress "Reading/Building" progress messages. 
    --random     Build dependencies in random order. 
    -s, --silent, --quiet  Don't print commands. 
    --site-dir=DIR    Use DIR instead of the usual site_scons dir. 
    --stack-size=N    Set the stack size of the threads used to run 
           jobs to N kilobytes. 
    --taskmastertrace=FILE  Trace Node evaluation to FILE. 
    --tree=OPTIONS    Print a dependency tree in various formats: all, 
           derived, prune, status. 
    -u, --up, --search-up  Search up directory tree for SConstruct, 
           build targets at or below current directory. 
    -U       Search up directory tree for SConstruct, 
           build Default() targets from local SConscript. 
    -v, --version    Print the SCons version number and exit. 
    --warn=WARNING-SPEC, --warning=WARNING-SPEC 
           Enable or disable warnings. 
    -Y REPOSITORY, --repository=REPOSITORY, --srcdir=REPOSITORY 
           Search REPOSITORY for source and target files. 

Local Options: 
    -V, --verbose    Print everything to stdout 

+ scons --version 
SCons by Steven Knight et al.: 
    script: v2.3.4, 2014/09/27 12:51:43, by garyo on lubuntu 
    engine: v2.3.4, 2014/09/27 12:51:43, by garyo on lubuntu 
    engine path: ['/usr/lib/scons/SCons'] 
Copyright (c) 2001 - 2014 The SCons Foundation 

+ scons -v 
SCons by Steven Knight et al.: 
    script: v2.3.4, 2014/09/27 12:51:43, by garyo on lubuntu 
    engine: v2.3.4, 2014/09/27 12:51:43, by garyo on lubuntu 
    engine path: ['/usr/lib/scons/SCons'] 
Copyright (c) 2001 - 2014 The SCons Foundation 

+ scons 
scons: Reading SConscript files ... 
## VERBOSITORY IS OFF ## 
scons: done reading SConscript files. 
scons: Building targets ... 
scons: `.' is up to date. 
scons: done building targets. 

+ scons --verbose 
scons: Reading SConscript files ... 
## VERBOSITORY IS ON ## 
scons: done reading SConscript files. 
scons: Building targets ... 
scons: `.' is up to date. 
scons: done building targets. 

+ scons -V 
usage: scons [OPTION] [TARGET] ... 

SCons Error: no such option: -V 

Так почему я получаю ошибку при прохождении -V?

ответ

1

Сценарий несколько раз анализирует список аргументов. Ваша ошибка связана с первым пропуском, даже до того, как считываются SConscripts, и разрешены только встроенные аргументы ... так что ваш AddOption() еще не имеет эффекта.

На самом деле, невозможно добавить короткий вариант, например, «-V» методом AddOption в SConscript. Только длинные варианты, такие как ваш «--verbose», не нарушают сборку сразу. В src/engine/Script/SConsOptions.py метод SConsOptionParser._process_long_opt() ловит фактическое исключение, так что во второй попытке (после прочтения во всех SConscripts/SConstructs) синтаксический анализ может быть успешным.

+0

Значит, это ошибка у браслетов? Руководство пользователя говорит: «Функция AddOption принимает те же аргументы, что и функция optparse.add_option из стандартной библиотеки Python». Поскольку мой вариант был сделан главным образом из первого примера в документации optparse, я думаю, что это ошибка ... Кроме того, я бы не сказал, что невозможно добавить короткий вариант, например -V, если я не используйте эту опцию, она отлично работает и даже появляется в диалоговом окне справки. По общему признанию, это не очень полезно, но усиливает мне, что это, вероятно, ошибка. –

+0

Вы можете видеть это как ошибку, конечно. Но для меня это скорее отсутствие надлежащей документации. Насколько мне известно, в документах SCons (* not * optparse one) вы не найдете пример добавления короткой опции ... так что это дает несколько подсказку. ;) Могли бы вы сообщить об этом как о проблеме нашему трекеру Tigris? Тогда это не забыто, и кто-то может исправить документы. – dirkbaechle

Смежные вопросы