def test_GPSTime_from_yaml(): yaml = ruamel.yaml.YAML(typ="unsafe") yaml.register_class(GPSTime) current_yaml_format = """ !GPSTime femtoseconds: 200000000000000 seconds: 23234 week_number: 213 """ current_format: GPSTime = yaml.load(current_yaml_format) assert isinstance(current_format, GPSTime) assert hasattr(current_format, "week_number") assert hasattr(current_format, "seconds") assert hasattr(current_format, "femtoseconds") assert current_format.week_number == 213 assert current_format.seconds == 23234 assert current_format.femtoseconds == 200000000000000 assert current_format.time_of_week == 23234.2 legacy_yaml_format = """ !GPSTime time_of_week: 23234.2 week_number: 213 """ legacy_format: GPSTime = yaml.load(legacy_yaml_format) assert isinstance(legacy_format, GPSTime) assert hasattr(legacy_format, "week_number") assert hasattr(legacy_format, "seconds") assert hasattr(legacy_format, "femtoseconds") assert legacy_format.week_number == 213 assert legacy_format.seconds == 23234 assert np.isclose(legacy_format.femtoseconds, 200000000000000) assert legacy_format.time_of_week == 23234.2
def save_to_file(self, cfg_path: Path) -> None: cfg_path.parent.mkdir(parents=True, exist_ok=True) yaml = ruamel.yaml.YAML(typ="rt") yaml.register_class(Path) as_dict = attr.asdict(self) with cfg_path.open("w") as fp: yaml.dump(as_dict, fp)
def init_dv_model(yaml_model_file): global DV_MODEL if not DV_MODEL: yaml = ruamel.yaml.YAML() yaml.register_class(DVModel) yaml.register_class(Hub) yaml.register_class(Sat) yaml.register_class(Link) yaml.register_class(SatLink) with open(yaml_model_file) as yf: DV_MODEL = yaml.load(yf) DV_MODEL.init_model()
def current(): """Prints the current configuration """ yaml.register_class(profile.ProfileData) #yaml.register_class(dict) builder_data.register_classes(yaml) data = { 'profile': profile.get(), 'builder': { 'filepath': builder_data.get_storage_filepath(), #'data': builder_data.get() } } yaml.dump(data, sys.stdout)
def register_classes( yaml: ruamel.yaml.YAML, classes: Optional[Iterable[Any]] = None) -> ruamel.yaml.YAML: """Register externally defined classes.""" # Validation if classes is None: classes = [] # Register the classes for cls in classes: logger.debug(f"Registering class {cls} with YAML") yaml.register_class(cls) return yaml
def load_config(cls: Type['Flow'], filename: Union[str, TextIO]) -> 'Flow': """Build an executor from a YAML file. :param filename: the file path of the YAML file or a ``TextIO`` stream to be loaded from :return: an executor object """ yaml.register_class(Flow) if not filename: raise FileNotFoundError if isinstance(filename, str): # deserialize from the yaml with open(filename, encoding='utf8') as fp: return yaml.load(fp) else: with filename: return yaml.load(filename)
def convert_to_yaml(resume: Resume, destination: str): yaml = ruamel.yaml.YAML() resume_types = [Basics, Resume, Volunteer, Education, Skill, Award, Publication, Language, Interest, Project, Reference, Profile, Work, Location] [yaml.register_class(resume_type) for resume_type in resume_types] with open(destination, 'w+') as f: yaml.dump(resume, f)
def save_config(self, filename: str = None) -> bool: """ Serialize the object to a yaml file :param filename: file path of the yaml file, if not given then :attr:`config_abspath` is used :return: successfully dumped or not """ f = filename if not f: f = tempfile.NamedTemporaryFile('w', delete=False, dir=os.environ.get('JINA_EXECUTOR_WORKDIR', None)).name yaml.register_class(Flow) # yaml.sort_base_mapping_type_on_output = False # yaml.representer.add_representer(OrderedDict, yaml.Representer.represent_dict) with open(f, 'w', encoding='utf8') as fp: yaml.dump(self, fp) self.logger.info(f'{self}\'s yaml config is save to %s' % f) return True
def save_jailhouse_config(path: Path, config: Optional[JailhouseConfig]) -> None: if config is not None: with path.open("w") as f: yaml = ruamel.yaml.YAML() yaml.register_class(HexInt) yaml.register_class(ByteSize) yaml.register_class(IntegerList) yaml.register_class(JailhouseFlagList) yaml.register_class(ExpressionInt) yaml.representer.add_representer(IPv4Interface, repr_string) yaml.representer.add_representer(IPv4Network, repr_string) yaml.representer.add_representer(IPv6Interface, repr_string) yaml.representer.add_representer(IPv6Network, repr_string) cells_dict = config.dict(exclude_unset=True, exclude_defaults=True) yaml.dump(cells_dict, f)
def createBootYaml(destPath): yaml = ruamel.yaml.YAML() yaml.register_class(FAT32BootParameter) yaml.register_class(FAT32FsInfoParameter) yaml.register_class(FAT32Parameter) bootparam = FAT32BootParameter( chJumpInstruction=b'\xEB\x58\x90', chOemId='EX-DIROP', wBytesPerSector=512, uchSectorsPerCluster=2, wRsvdSectorsCount=32, uchFatCopies=2, wMaxRootEntries=0, wTotalSectors=0, uchMediaDescriptor=0xF8, wSectorsPerFat=0, wSectorsPerTrack=63, wHeads=16, wHiddenSectors=0, dwSectorsPerFat=0, dwRootCluster=2, wFSISector=1, wBootCopySector=6, chReserved=b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', chPhysDriveNumber=0x80, chReserved1=0x00, chExtBootSignature=0x29, wBootSignature=0xAA55, dwVolumeID=1234567890, sVolumeLabel='M111', sFSType='FAT32') fsinfo = FAT32FsInfoParameter(sSignature1='RRaA', sReserved1='', sSignature2='rrAa', dwFreeClusters=0, dwNextFreeCluster=3, sReserved2='', wBootSignature=0xAA55) fat32 = FAT32Parameter(bootparam, fsinfo) with open(os.path.join(destPath, 'fat32boot.yml'), 'w') as outfile: yaml.dump(bootparam, outfile) with open(os.path.join(destPath, 'fsinfo.yml'), 'w') as outfileFSI: yaml.dump(fsinfo, outfileFSI) with open(os.path.join(destPath, 'fat32.yml'), 'w') as outfileParam: yaml.dump(fat32, outfileParam)
def main(): import sys yaml = ruamel.yaml.YAML() yaml.register_class(Item) yaml.register_class(Folder) yaml.register_class(Family) yaml.register_class(Software) yaml.dump(setting, sys.stdout) print() with open(setting['make']['source_file_path'], "r", encoding='utf-8') as fd: items = yaml.load(fd.read()) print("[ STATUS ] yaml.load() Done.") print("[ METHOD ] [ TYPE ] H L | item.__dict__") with open(setting['make']['destination_file_path'], "w", encoding='utf-8', buffering=1) as fd: recur( fd, Markdown(setting['markdown']['indenting_spaces'], setting['markdown']['style_indicator']), setting['make']['flags_filter'], items, 2) print("[ STATUS ] recur() Done.") if setting['merge']['enable'] is True: merge([ setting['merge']['head_file_path'], setting['make']['destination_file_path'], setting['merge']['tail_file_path'] ], setting['merge']['output']) if setting['merge']['append_timestamp']: with open(setting['merge']['output'], 'a', encoding='utf-8') as fd: import time print_and_write(fd, "- Build: {}\n".format(time.ctime())) print("[ STATUS ] append_timestamp") print("[ STATUS ] merge() Done.")
def __init__(self, filename=None, Tables=None, object=None): self.filename = filename self.tables = [] if tables is None else tables self.object = object @classmethod def from_yaml(cls, constructor, node): for m in constructor.construct_yaml_map(node): pass if 'Name' in m: filename = m['FileName'] elif 'columns' in m: columns = m['Columns'] else: name = None object = m['object'] if 'object' in m else None return cls(filename, tables, object) def __repr__(self): return 'Message(filename={}, tables={}, object={})'.format( self.filename, self.tables, self.object) if __name__=="__main__": yaml = ruamel.yaml.YAML(typ='safe') yaml.register_class(Version) #yaml.register_class(Message) with open('etl.yaml') as fp: data = yaml.load(fp) print(data)
def register_classes(classes): for c in classes: yaml.register_class(c)
yaml.dump(self, output) return output.getvalue() @classmethod def to_yaml(cls, representer, data): return representer.represent_mapping(cls.yaml_tag, {'hx': data.hx, 'hy': data.hy, 'hz': data.hz, 'cx': data.cx, 'cy': data.cy, 'cz': data.cz, 'rx': data.rx, 'ry': data.ry, 'rz': data.rz}) @classmethod def from_yaml(cls, constructor, node): return cls(*node.value) yaml.register_class(CrystalCubic) class Experiment: def __init__(self): self.crystal_shape = None self.source = None self.surface = None self.detectors = None self.nb_runs = None self.target_path = None def _make_data_processing(self): pass def make(self):
# load_pr = json.loads(ser_pr, object_hook=from_json) # print("Look here we have our programmer") # print(type(load_pr), load_pr) # except TypeError as e: # print(e) # # try: # load_pr = json.loads(ser_pr, object_hook=from_json) # print("Look here we have our programmer") # print(type(load_pr), load_pr) # except TypeError as e: # print(e) # Lets dump object to pickle with open("data.txt", "wb") as file: pickle.dump(auto, file) # # Lets load it with open("data.txt", "rb") as file: restore_obj = pickle.load(file) print(type(restore_obj), restore_obj) yaml = ruamel.yaml.YAML() yaml.register_class(Car) yaml.dump(auto, sys.stdout) # with open("data.yaml", "w") as file: # yaml.dump(auto, file) # print("Success!") with open("data.yaml", "r") as file: config = yaml.load(file) print(type(config), config)
parser = argparse.ArgumentParser() parser.add_argument('csvFile', help = 'input CSV file') parser.add_argument('-o','--outputPath', help = 'output path') arguments = parser.parse_args() if not arguments.outputPath: arguments.outputPath = os.path.dirname(arguments.csvFile) + '/chipYaml' year = datetime.date.today().year with open(arguments.csvFile) as csvFile: csvReader = csv.reader(csvFile) firstRow = next(csvReader) paths, labels = parseFirstRow(firstRow) yaml = ruamel.yaml.YAML() yaml.register_class(Reference) for row in csvReader: yamlFilename = os.path.join(arguments.outputPath, common.sanitize(parseString(row[0])[0]) + '.yaml') print('Generating {}...'.format(yamlFilename)) with open(yamlFilename, 'w') as yamlFile: dictionary = parseRow(row, paths) dictionary = addLabels(dictionary, labels) yamlFile.write("#\n" "# file: {}\n" "#\n" "# author: Copyright (C) {} Kamil Szczygiel http://www.distortec.com " "http://www.freddiechopin.info\n" "#\n" "# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a " "copy of the MPL was not\n" "# distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.\n"
@classmethod def to_yaml(cls, dumper, data): return dumper.represent_yaml_object(cls.yaml_tag, ReachConfigOut(data, data._node), cls) # represents the unaltered yaml nodes for the reachability # for the purpose of printing out the "in" nodes we # actually use class ReachConfigOut: def __init__(self, data, node): self.addServerProgress = int(node[0][1].value) self.coldCache = (node[1][1].value == "true") self.d = int(node[2][1].value) self.s = int(node[3][1].value) # register the "in" class with the reader yaml.register_class(ReachConfigIn) # reads the nodes and edges of the reachability graph # from the yaml file output by reach.sh def loadReachability(): with open("%s/reach/rubis.yaml" % results_dir, 'r') as f: docs = yaml.load_all(f) return next(docs), next(docs) def check(base,child): pattern = "%2d,%2d,%2d -> %2d,%2d,%2d .* : \\+" % (base.s,2-(base.p-1),base.d-1,child.s,2-(child.p-1),child.d-1) with open("%s/trim%s/trimmed.txt" % (results_dir,weights), 'r') as f: for line in f: if re.match(pattern, line): return True return False
print(ces) print(ces.cars_count()) # if __name__ == "__main__": # ser_gr = '' # with open('data3.json', 'w') as file: # # ser_pr = json.dump(autos, file, default=to_json) # json.dump(ces, file, default=to_json, indent=4) # print("Success") # # with open('data3.json') as f: # load_ser_pr = json.load(f, object_hook=from_json) # print(type(load_ser_pr), load_ser_pr) # with open("data3.txt", "wb") as file: # pickle.dump(ces, file) # # # Lets load it # with open("data3.txt", "rb") as file: # restore_obj = pickle.load(file) # print(type(restore_obj), restore_obj) yaml = ruamel.yaml.YAML() yaml.register_class(Cesar) yaml.dump(ces, sys.stdout) # with open("data3.yaml", "w") as file: # yaml.dump(ces, file) # print("Success!") with open("data3.yaml", "r") as file: config = yaml.load(file) print(type(config), config)
# _______Create Cesar, Garage and Car from JSON files______ with open('heorh.json', 'r') as file: decoded_cesar = json.load(file, object_hook=cesar_from_json) with open('king_garage.json', 'r') as file: decoded_garage = json.load(file, object_hook=garage_from_json) with open('elite_car.json', 'r') as file: decoded_car = json.load(file, object_hook=car_from_json) # ___________convert by YAML____________ # _______save Ceser Car and Garage by yaml______ yaml = YAML() yaml.register_class(Cesar) with open('heorh.yaml', 'w') as file: ruamel.yaml.dump(heorh, file) yaml.register_class(Garage) with open('king_garage.yaml', 'w') as file: ruamel.yaml.dump(king_garage, file) yaml.register_class(Car) with open('elite_car.yaml', 'w') as file: ruamel.yaml.dump(elite_car, file) # ______Create Cesar, Garage and Car from YAML_______ with open('heorh.yaml', 'r') as file: heorh = ruamel.yaml.load(file)
def register_classes(yaml): yaml.register_class(UserPath) yaml.register_class(Container) yaml.register_class(HttpRequest) yaml.register_class(Container) yaml.register_class(Transaction) yaml.register_class(Delay) yaml.register_class(RampPolicy) yaml.register_class(ConstantPolicy) yaml.register_class(Population) yaml.register_class(Scenario) yaml.register_class(Header) yaml.register_class(Extractor) yaml.register_class(SLA) yaml.register_class(VariableTypeJavascript) yaml.register_class(JavascriptAction)
class Setup: def __init__(self): self.jira_username = '' self.jira_key = '' self.jira_host = "" self.current_issues = [] self.development_branch = "" self.hotfix_branch = "" self.production_branch = "" self.current_branch = "" self.current_type = "" yaml.register_class(Setup) class StorageHandler: def __init__(self): self.__options = Setup() pass def check_init(self): if not os.path.exists(".JAGtool"): with open(".JAGtool", "w") as f: yaml.dump([self.__options], f) with open(".JAGtool", "r") as f: y = yaml.load(f) print(y[0])
ObjectId.yaml_tag = u'!bson.objectid.ObjectId' ObjectId.to_yaml = classmethod( lambda cls, representer, node: representer.represent_scalar( cls.yaml_tag, u'{}'.format(node))) ObjectId.from_yaml = classmethod( lambda cls, constructor, node: cls(node.value)) Int64.yaml_tag = u'!bson.int64.Int64' Int64.to_yaml = classmethod(lambda cls, representer, node: representer. represent_scalar(cls.yaml_tag, u'{}'.format(node))) Int64.from_yaml = classmethod(lambda cls, constructor, node: cls(node.value)) yaml = ruamel.yaml.YAML(typ="safe") yaml.default_flow_style = False yaml.register_class(ObjectId) yaml.register_class(Int64) """ Class to be used as a template for rules which require python scripts. Can be tightened up to only allow access to parts of the document if needed in the future, ie options. """ class stamperTestObj: def __init__(self, function_name, display_name, effect, log=None): self.name = function_name self.display_name = display_name self.effect = effect self.value = "" self.status = "" self.reason = ""
def test_dump_object(self): box = config.BoxModel() yaml = ruamel.yaml.YAML() yaml.register_class(ConditionParams) yaml.dump({'formation': {'enter': {'box_model': box}}}, sys.stdout)
import ruamel.yaml import logging import json import multiprocessing import itertools import os.path import re import pprint import os import shutil log = logging.getLogger(LOGGER_NAME) pp = pprint.PrettyPrinter(2) yaml = ruamel.yaml.YAML() yaml.register_class(RT) runtime_vars = { "$team1": "${team1}", "$team2": "${team2}", } """ rts[comment] = { regex: str, rt: RT, SOPairs: [(section, outcome)] } """ rts = {} loaded_from_backup = False CONF_FILE = "rts.yml"
Stores the current configuration in CONFIG_PATH """ with open(CONFIG_PATH, 'w') as f: yaml.dump(self, f) def load(self): """ Loads the configuration stored in CONFIG_PATH """ stored_config = Path(CONFIG_PATH) if stored_config.is_file(): with open(CONFIG_PATH, 'r') as f: stored_config = yaml.load(f) self.ldap_uri = stored_config.ldap_uri self.ldap_secret = stored_config.ldap_secret self.org = stored_config.org self.admin = stored_config.admin self.people = stored_config.people self.groups = stored_config.groups self.timeout = stored_config.timeout yaml.register_class(Config) config = Config() """ config should be the only instance of this class. For accessing or modifying the configuration, config should be used. """
def handle(self) -> int: if not self.autojail_config: self.line(f"<error>could not find {self.CONFIG_NAME}</error>") return 1 cells_yml_path = Path.cwd() / self.CELLS_CONFIG_NAME if not cells_yml_path.exists(): self.line(f"<error>{cells_yml_path} could not be found</error>") return 1 board_yml_path = Path.cwd() / self.BOARD_CONFIG_NAME if not board_yml_path.exists(): self.line(f"<error>{board_yml_path} could not be found</error>") self.line("Please run <comment>automate extract</comment> first") return 1 with board_yml_path.open() as f: yaml = ruamel.yaml.YAML() board_dict = yaml.load(f) board_info = Board(**board_dict) set_params = None if self.option("set-params"): params_yml_path = self.option("set-params") if params_yml_path == "null": params_yml_path = "set-params.yml" params_yml_path = Path(params_yml_path) if not params_yml_path.exists(): self.line( f"<error>{params_yml_path} could not be found</erro>") return 1 with params_yml_path.open() as f: yaml = ruamel.yaml.YAML() params_dict = yaml.load(f) set_params = GenerateConfig(**params_dict) gen_params = None if self.option("generate-params"): gen_params = GenerateParameters() configurator = JailhouseConfigurator( board_info, self.autojail_config, print_after_all=self.option("print-after-all"), context=self.automate_context, set_params=set_params, gen_params=gen_params, ) configurator.read_cell_yml(str(cells_yml_path)) configurator.prepare() if gen_params: gen_params_yml_path = self.option("generate-params") if gen_params_yml_path == "null": gen_params_yml_path = "explore-params.yml" gen_params_yml_path = Path(gen_params_yml_path) with gen_params_yml_path.open("w") as f: yaml = ruamel.yaml.YAML() yaml.register_class(ScalarChoice) yaml.register_class(Partitions) yaml.register_class(GenerateParameters) yaml.dump(gen_params.dict(), f) ret = configurator.write_config(self.autojail_config.build_dir) if ret or self.option("generate-only"): if ret: configurator.report() return ret ret = configurator.build_config(self.autojail_config.build_dir, skip_check=self.option("skip-check")) if ret: configurator.report() return ret ret = configurator.deploy( self.autojail_config.build_dir, self.autojail_config.deploy_dir, target=self.option("target"), ) configurator.report() return ret
return 'Version(header={.header}, count={.count}, row={.row}, tablenake={.tablename})'.format(self, self, self, self) # produce = ["Apple", # "Grapes", # "Almonds", # "Walnuts", # "Pears", # "Oranges"] # # count = 500 # fname = "input.csv" # with open(fname, "w+") as f: # f.write("Produce,Qty,Price\n") # for i in range(0, count): # p = produce[random.randint(0, len(produce)-1)] # qty = random.randint(1,10) # price = random.uniform(1.5, 10.0) # f.write('"{}",{},{}\n'.format(p,qty,price)) if __name__=="__main__": yaml = ruamel.yaml.YAML(typ='safe') yaml.register_class(CsvGen) yaml.register_class(ListPick) #yaml.register_class(Message) with open('CsvGen.yml') as fp: data = yaml.load(fp) print(type(data))
def yaml_spec(self): yaml.register_class(Flow) stream = StringIO() yaml.dump(self, stream) return stream.getvalue().strip()
######################################################################################################################## if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('inputFile', type = argparse.FileType('r'), help = 'input file') parser.add_argument('-o', '--outputPath', help = 'output path') parser.add_argument('-d', '--distortosPath', help = 'distortos path') arguments = parser.parse_args() if not arguments.outputPath: arguments.outputPath = os.path.dirname(arguments.inputFile.name) if not arguments.distortosPath: arguments.distortosPath = os.path.relpath(sys.argv[0] + '/../..') yaml = ruamel.yaml.YAML() yaml.register_class(Reference) dictionary = yaml.load(arguments.inputFile) dictionary = resolveExtensions(dictionary, arguments.distortosPath) labels = getLabels(dictionary) resolveReferences(dictionary, labels) addPaths(dictionary) # in case of "raw" board - generated directly from chip YAML file - use chip name as board board = dictionary.get('board', dictionary['chip'])['compatible'][0] relativeDistortosPath = posixpath.relpath(posixpath.realpath(arguments.distortosPath), posixpath.realpath(arguments.outputPath)) relativeOutputPath = posixpath.relpath(posixpath.realpath(arguments.outputPath), posixpath.realpath(arguments.distortosPath))
def callfct(function_call, error_expected=None): if error_expected: with pytest.raises(Exception) as e: function_call() #TODO: not sure next line is executed at all????? assert e.value.__class__ == error_expected else: function_call() ## ------------------------------------------------------------------------------------------- ## ## Test yaml Loading of model and model rules checks ## ------------------------------------------------------------------------------------------- ## yaml = ruamel.yaml.YAML() yaml.register_class(DVModel) yaml.register_class(Hub) yaml.register_class(Sat) yaml.register_class(Link) yaml.register_class(SatLink) def test_yaml_and_resolve_atts(): y_t = """ tables: hub: &hub !Hub name: myhub nat_keys: - {name: h1_id, format: number(9)} - {name: h2_id} sur_key: {} list_vals:
parser.add_argument('--navigation', help='navigation file', type=str, default='pages/navigation.yml') parser.add_argument('--no-optimize', action='store_false', help='disable HTML minification') args = parser.parse_args() loader = jinja2.PrefixLoader( {'template': jinja2.FileSystemLoader(args.template)}, delimiter='@') env = jinja2.Environment(loader=loader, autoescape=jinja2.select_autoescape()) yaml = ruamel.yaml.YAML() yaml.register_class(Section) with open(args.navigation) as f: root_section = yaml.load(f) page_meta = read_meta(args.input) page_source = args.input.read() page_source = env.from_string(page_source).render(meta=page_meta, home=root_section) page_content = markdown.markdown( page_source, extensions=('markdown.extensions.toc', 'markdown.extensions.footnotes'))
import pkg_resources import ruamel.yaml from bifrostlib import mongo_interface import bson import os bson.objectid.ObjectId.yaml_tag = u'!bson.objectid.ObjectId' bson.objectid.ObjectId.to_yaml = classmethod( lambda cls, representer, node: representer.represent_scalar( cls.yaml_tag, u'{}'.format(node))) bson.objectid.ObjectId.from_yaml = classmethod( lambda cls, constructor, node: cls(node.value)) yaml = ruamel.yaml.YAML(typ="safe") yaml.default_flow_style = False yaml.register_class(bson.objectid.ObjectId) def connect_or_initialize_and_connect(config): mongo_interface.set_connection_key_location(config) def log(log_file, content): with open(log_file, "a+") as file_handle: file_handle.write(content) def load_config(): config_file = "run_config.yaml" if not os.path.isfile("run_config.yaml"): config_file = "../run_config.yaml"
import os import sys from pathlib import Path import click import ldap import ruamel.yaml from .params import * from .config import config, Config from .model import Person, Group yaml = ruamel.yaml.YAML() yaml.register_class(Person) yaml.register_class(Group) yaml.register_class(Config) def sudo(): """ Checks that the program is running as root, otherwise asks for permissions and it runs again. """ euid = os.geteuid() if euid != 0: print("Script not started as root. Running sudo...") args = ['sudo', sys.executable] + sys.argv + [os.environ] os.execlpe('sudo', *args) # Replaces the current process with the sudo print("Running as sudo") def get_ldap_password():