def custom_exec(cmd): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") cmd_index = next(index for (index, d) in enumerate(correspondance) if d["name"] == cmd[1]) for commande in correspondance[cmd_index]['commande']: cmd[1] = commande print('before exec : ', getattr(django_settings, 'DEBUG')) execute_from_command_line(cmd)
def _setup_media_dirs(self): self.tempdir = tempfile.mkdtemp(prefix='rb-tests-') # Don't go through Pipeline for everything, since we're not # triggering pipelining of our media. settings.STATICFILES_STORAGE = \ 'django.contrib.staticfiles.storage.StaticFilesStorage' if os.path.exists(self.tempdir): self._destroy_media_dirs() settings.STATIC_ROOT = os.path.join(self.tempdir, 'static') settings.MEDIA_ROOT = os.path.join(self.tempdir, 'media') settings.SITE_DATA_DIR = os.path.join(self.tempdir, 'data') images_dir = os.path.join(settings.MEDIA_ROOT, "uploaded", "images") legacy_extensions_media = os.path.join(settings.MEDIA_ROOT, 'ext') extensions_media = os.path.join(settings.STATIC_ROOT, 'ext') for dirname in (images_dir, legacy_extensions_media, extensions_media): if not os.path.exists(dirname): os.makedirs(dirname) # Collect all static media needed for tests, including web-based tests. execute_from_command_line([ __file__, 'collectstatic', '--noinput', '-v', '0', ]) generate_media_serial()
def init_config(args): """ Initialize configs of the service. Do the following things: 1. automl board settings 2. database settings 3. django settings """ os.environ["AUTOMLBOARD_LOGDIR"] = args.logdir os.environ["AUTOMLBOARD_LOGLEVEL"] = args.log_level os.environ["AUTOMLBOARD_RELOAD_INTERVAL"] = str(args.reload_interval) if args.db: try: db_address_reg = re.compile(r"(.*)://(.*):(.*)@(.*):(.*)/(.*)") match = re.match(db_address_reg, args.db_address) os.environ["AUTOMLBOARD_DB_ENGINE"] = match.group(1) os.environ["AUTOMLBOARD_DB_USER"] = match.group(2) os.environ["AUTOMLBOARD_DB_PASSWORD"] = match.group(3) os.environ["AUTOMLBOARD_DB_HOST"] = match.group(4) os.environ["AUTOMLBOARD_DB_PORT"] = match.group(5) os.environ["AUTOMLBOARD_DB_NAME"] = match.group(6) logger.info("Using %s as the database backend." % match.group(1)) except BaseException as e: raise DatabaseError(e) else: logger.info("Using sqlite3 as the database backend, " "information will be stored in automlboard.db") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ray.tune.automlboard.settings") django.setup() command = [os.path.join(root_path, 'manage.py'), 'migrate', '--run-syncdb'] execute_from_command_line(command)
def main(settings, in_subprocess): if dirname(settings.__file__) == os.getcwd(): sys.stderr.write("manage.py should not be run from within the " "'reviewboard' Python package directory.\n") sys.stderr.write("Make sure to run this from the top of the " "Review Board source tree.\n") sys.exit(1) if (len(sys.argv) > 1 and (sys.argv[1] == 'runserver' or sys.argv[1] == 'test')): if settings.DEBUG and not in_subprocess: sys.stderr.write('Running dependency checks (set DEBUG=False ' 'to turn this off)...\n') check_dependencies(settings) if sys.argv[1] == 'runserver': # Force using HTTP/1.1 for all responses, in order to work around # some browsers (Chrome) failing to consistently handle some # cache headers. simple_server.ServerHandler.http_version = '1.1' else: # Some of our checks require access to django.conf.settings, so # tell Django about our settings. # # Initialize Review Board, so we're in a state ready to load # extensions and run management commands. from reviewboard import initialize initialize() include_enabled_extensions(settings) execute_from_command_line(sys.argv)
def main(): settings.configure( DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', } }, INSTALLED_APPS = ( 'django.contrib.staticfiles', 'cookielaw', 'cookielaw.test_project.test_app', ), TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.debug', 'django.core.context_processors.i18n', 'django.core.context_processors.media', 'django.core.context_processors.request', 'django.core.context_processors.static', 'django.core.context_processors.tz', 'django.contrib.messages.context_processors.messages' ), ROOT_URLCONF = 'cookielaw.test_project.urls', STATIC_URL = '/static/', ) management.execute_from_command_line(['', 'test', 'cookielaw',]) sys.exit()
def run_board(args): """ Run main entry for AutoMLBoard. Args: args: args parsed from command line """ init_config(args) # backend service, should import after django settings initialized from backend.collector import CollectorService service = CollectorService( args.logdir, args.reload_interval, standalone=False, log_level=args.log_level) service.run() # frontend service logger.info("Try to start automlboard on port %s\n" % args.port) command = [ os.path.join(root_path, 'manage.py'), 'runserver', '0.0.0.0:%s' % args.port, '--noreload' ] execute_from_command_line(command)
def run_from_argv(self, argv): from django.db import connections for connection in connections.all(): if hasattr(connection, 'setup_remote'): connection.setup_remote() argv = argv[:1] + argv[2:] execute_from_command_line(argv)
def manage(project): sys.path.insert(0, os.path.join(os.getcwd(), project)) os.environ.setdefault('DJANGO_SETTINGS_MODULE', '{}.settings.development'.format(project)) with chdir(project): from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
def run_command_as_script(command_name): ''' Helper function to run the given management command directly as a script. Include something like the following in your management/commands/blah.py: if __name__ == '__main__': from __init__ import run_command_as_script command_name = os.path.splitext(os.path.basename(__file__))[0] run_command_as_script(command_name) ''' # The DJANGO_SETTINGS_MODULE environment variable should already be set if # the script is called from a celery task. settings_module_name = os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'lib.settings') # This sys.path hack is needed when a celery task calls ansible-playbook # and needs to execute the script directly. FIXME: Figure out if this will # work when installed in a production environment. try: settings_parent_module = __import__(settings_module_name) except ImportError: top_dir = os.path.join(os.path.dirname(__file__), '..', '..', '..', '..') sys.path.insert(0, os.path.abspath(top_dir)) settings_parent_module = __import__(settings_module_name) settings_module = getattr(settings_parent_module, settings_module_name.split('.')[-1]) # Use the ACOM_TEST_DATABASE_NAME environment variable to specify the test # database name when called from unit tests. if os.environ.get('ACOM_TEST_DATABASE_NAME', None): settings_module.DATABASES['default']['NAME'] = os.environ['ACOM_TEST_DATABASE_NAME'] from django.core.management import execute_from_command_line argv = [sys.argv[0], command_name] + sys.argv[1:] execute_from_command_line(argv)
def main(): profile = os.environ.setdefault("movie_crawler_PROFILE", "dev") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "movie_crawler.settings.%s" % profile) from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
def handle(self, *settings, **options): cmd = options.get('exec') if not cmd: raise CommandError('You have to specify a command to run with these settings.') set_settings(settings) cmd = sys.argv[:1] + expand_shell(cmd) execute_from_command_line(cmd)
def _execute_cmd(cmd, mod_settings_obj = '', exec_dir = ''): ''' Receives cmd, containing command to execute, and its options as a list, and, optionally, the settings file for that stack, and the directory to execute the command from. Imports the Django execute from command line functions and executes cmd in it. ''' if cmd[0] not in ('django_admin.py', 'manage.py'): if mod_settings_obj == '': sys.argv = ['django_admin.py'] + cmd else: sys.argv = ['manage.py'] + cmd os.environ.setdefault("DJANGO_SETTINGS_MODULE", mod_settings_obj) elif cmd[0] == 'manage.py': sys.argv = cmd os.environ.setdefault("DJANGO_SETTINGS_MODULE", mod_settings_obj) pwd = os.getcwd() if os.path.isdir(exec_dir): os.chdir(exec_dir) from django.core.management import execute_from_command_line sys.path.append(exec_dir) execute_from_command_line(sys.argv) sys.path.remove(exec_dir) os.chdir(pwd)
def django(ctx, management_args): os.environ.setdefault( 'DJANGO_SETTINGS_MODULE', '{{ project_name }}.service.settings.common' ) from django.core.management import execute_from_command_line execute_from_command_line(argv=[ctx.command_path] + list(management_args))
def handle(self, **options): """See :meth:`django.core.management.base.BaseCommand.handle`. This method loads all of the fixtures into the database. """ logger.info('Command starting: load_all_data') fixture_names = [] manage_path = os.path.join(settings.BASE_DIR, 'manage.py') for app_dir in os.listdir(settings.BASE_DIR): app_dir_path = os.path.join(settings.BASE_DIR, app_dir) if not os.path.isdir(app_dir_path): continue sub_dirs = os.listdir(app_dir_path) if 'fixtures' in sub_dirs: fixture_dir_path = os.path.join(app_dir_path, 'fixtures') for entry in os.listdir(fixture_dir_path): if os.path.isfile(os.path.join(fixture_dir_path, entry)): if entry.endswith('.json'): logger.info('Discovered: %s -> %s', app_dir, entry) fixture_names.append(entry) for name in fixture_names: cmd_list = [manage_path, 'loaddata', name] logger.info('Executing: %s', ' '.join(cmd_list)) execute_from_command_line(cmd_list) logger.info('Command completed: load_all_data')
def main(apps, *args, **config): argv = config.pop('argv', sys.argv) environ = config.pop('environ', os.environ) full_settings = {} # TODO: Once Python 2.6 support can be dropped, switch back to dict comp full_settings.update(dict( (key, value) for key, value in vars(defaults).items() if key.isupper() )) argv = list(argv) with ensure_cleanup() as cleanup: for key, value in config.items(): if isinstance(value, DynamicSetting): cleanup.append(value.cleanup) full_settings[key] = value.get_value(argv, environ) else: full_settings[key] = value for arg in args: arg.process(argv, environ, full_settings) for app in apps: if app not in full_settings['INSTALLED_APPS']: full_settings['INSTALLED_APPS'].append(app) settings.configure(**full_settings) from django.core.management import execute_from_command_line execute_from_command_line(argv)
def create_project(): # Put mezzanine.conf in INSTALLED_APPS so call_command can find # our command, settings.configure() settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + ['mezzanine.bin'] argv = sys.argv[:1] + ['mezzanine_project'] + sys.argv[1:] management.execute_from_command_line(argv)
def main(settings): if dirname(settings.__file__) == os.getcwd(): sys.stderr.write("manage.py should not be run from within the " "'reviewboard' Python package directory.\n") sys.stderr.write("Make sure to run this from the top of the " "Review Board source tree.\n") sys.exit(1) if len(sys.argv) > 1 and \ (sys.argv[1] == 'runserver' or sys.argv[1] == 'test'): if settings.DEBUG: # If DJANGO_SETTINGS_MODULE is in our environment, we're in # execute_from_command_line's sub-process. It doesn't make sense # to do this check twice, so just return. if 'DJANGO_SETTINGS_MODULE' not in os.environ: sys.stderr.write('Running dependency checks (set DEBUG=False ' 'to turn this off)...\n') check_dependencies(settings) else: # Some of our checks require access to django.conf.settings, so # tell Django about our settings. # # Initialize Review Board, so we're in a state ready to load # extensions and run management commands. from reviewboard import initialize initialize() include_enabled_extensions(settings) execute_from_command_line(sys.argv)
def main(settings, in_subprocess): if dirname(settings.__file__) == os.getcwd(): sys.stderr.write("manage.py should not be run from within the " "'reviewboard' Python package directory.\n") sys.stderr.write("Make sure to run this from the top of the " "Review Board source tree.\n") sys.exit(1) if (len(sys.argv) > 1 and (sys.argv[1] == 'runserver' or sys.argv[1] == 'test')): if settings.DEBUG and not in_subprocess: sys.stderr.write('Running dependency checks (set DEBUG=False ' 'to turn this off)...\n') check_dependencies(settings) else: # Some of our checks require access to django.conf.settings, so # tell Django about our settings. # # Initialize Review Board, so we're in a state ready to load # extensions and run management commands. from reviewboard import initialize initialize() include_enabled_extensions(settings) execute_from_command_line(sys.argv)
def main(): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_server.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
def main(): # Note: main sometimes runs multiple times as a result of # execute_from_command_line trickery. This should be fine though. parser = argparse.ArgumentParser(description='Main script for running LeafLabeler') parser.add_argument('image_dir', type = str, help = 'Path to directory containing images (relative or absolute path)') parser.add_argument('image_list', type = str, help = 'List of image files to label this time.') parser.add_argument('label_output_file', type = str, help = 'Filename to write labels to.') args = parser.parse_args() proj_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'opensurfaces-segmentation-ui', 'example_project') #print 'inserting', proj_dir sys.path.insert(0, proj_dir) #print sys.path os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example_project.settings") # Export to environ for loading in LeafLabeler object (messy, but # easiest way to pass info from here into class) os.environ['leaflabeler_image_dir'] = args.image_dir os.environ['leaflabeler_image_list'] = args.image_list os.environ['leaflabeler_label_output_file'] = args.label_output_file from django.core.management import execute_from_command_line #execute_from_command_line(sys.argv) execute_from_command_line([sys.argv[0], 'runserver']) # hardcode runserver command
def entry(): _deprecation_check(sys.argv[0]) from django.core.exceptions import ImproperlyConfigured from django.core.management import execute_from_command_line, find_commands, find_management_module from django.core.management import LaxOptionParser from django.core.management.base import BaseCommand os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'desktop.settings') # What's the subcommand being run? # This code uses the same logic from django.core.management to handle command args argv = sys.argv[:] parser = LaxOptionParser(option_list=BaseCommand.option_list) parser.parse_args(argv) if len(argv) > 1: prof_id = subcommand = argv[1] else: prof_id = str(os.getpid()) try: # Let django handle the normal execution if os.getenv("DESKTOP_PROFILE"): _profile(prof_id, lambda: execute_from_command_line(sys.argv)) else: execute_from_command_line(sys.argv) except ImproperlyConfigured, e: if len(sys.argv) > 1 and sys.argv[1] == 'is_db_alive' and 'oracle' in str(e).lower(): sys.exit(10) else: raise e
def run(self): # Just default to production - if it's already set to something else, use that os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'stackdio.server.settings.production') # Import the needed arg from django.core.management import execute_from_command_line execute_from_command_line(self.args)
def main(): #os.chdir(os.environ.get('ZSW_DIR')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "zsw.zsw.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
def testmanage(*args): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.settings") sys.path.append(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tests')) sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tests', 'tests')) from django.core.management import execute_from_command_line execute_from_command_line(['manage.py'] + list(args))
def run_tests(self): basic_configuration('test') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "vaas.settings") from django.core.management import execute_from_command_line execute_from_command_line(['manage.py', 'test']) from atexit import _exithandlers del _exithandlers[:]
def run_tests(self): from django.core import management DSM = "DJANGO_SETTINGS_MODULE" if DSM not in os.environ: os.environ[DSM] = "easy_thumbnails.tests.settings" management.execute_from_command_line()
def runtests(): argv = sys.argv[:1] + ['test'] + sys.argv[1:] try: execute_from_command_line(argv) finally: shutil.rmtree(STATIC_ROOT, ignore_errors=True) shutil.rmtree(MEDIA_ROOT, ignore_errors=True)
def main(): """ Main entrance to OpenSlides. """ parser = get_parser() try: known_args, unknown_args = parser.parse_known_args() except UnknownCommand: unknown_command = True else: unknown_command = False if unknown_command: # Run a command, that is defined by the django management api local_installation = is_local_installation() setup_django_settings_module(local_installation=local_installation) execute_from_command_line(sys.argv) else: # Check for unknown_args. if unknown_args: parser.error('Unknown arguments {}'.format(' '.join(unknown_args))) # Save arguments, if one wants to access them later. arguments.set_arguments(known_args) # Run a command that is defined here # These are commands that can not rely on an existing settings known_args.callback(known_args)
def run_syncdb(): ''' Initialises a new database ''' print("* Intialising the database") # Only needed for update 1.1.1 > 1.2 from south.models import MigrationHistory from django.db.utils import DatabaseError from django.db import transaction from wger.manager.models import User with transaction.commit_on_success(): try: User.objects.count() new_db = False except DatabaseError: new_db = True transaction.rollback() # Create the tables execute_from_command_line(["", "syncdb", "--noinput"]) # Only needed for update 1.1.1 > 1.2 history = MigrationHistory.objects.count() if not history and not new_db: init_south() # Perform the migrations run_south() # Load fixtures load_fixtures()
def manage(): import os import sys from django.core.management import execute_from_command_line os.environ.setdefault("DJANGO_SETTINGS_MODULE", "saleor.settings") execute_from_command_line(sys.argv)
#!C:\Users\ASUS\Documents\TTLuis\venv\Scripts\python.exe from django.core import management if __name__ == "__main__": management.execute_from_command_line()
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoApp.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?") from exc execute_from_command_line(sys.argv)