def test_command_splitting(self): logger.debug('test_command started') cmd = 'echo foo' c = Command(cmd) self.assertEqual(c.args, cmd.split()) c = Command(cmd, shell=True) self.assertEqual(c.args, cmd)
def __init__(self, shell_binary, shell_argstr, return_code_echo_command, command_separator, is_interactive): """Sets up the context for a system shell process. Parameters ---------- shell_binary : str The shell binary, e.g. ``/bin/bash``, to start. shell_argstr : str Additional arguments to be passed to the shell at start. return_code_echo_command : str A command string in the shell's own language that prints to standard output the return code of the previously executed command. command_separator : str The character sequence to separate commands with. is_interactive : bool Whether the started shell is an interactive one. This does only change the behaviour of the context manager, to make the shell itself interactive, additional arguments in `shell_argstr` might need to be passed. """ self._args = shell_argstr self._binary = shell_binary # Note: The execution of the command and the reading of the output # has to happen BEFORE this timeout is hit, but a large timeout would # also mean waiting a lot for small commands, so this has to be # balanced carefully. self._capture = Capture(timeout=0.5, buffer_size=-1) self._command = Command(shell_binary + ' ' + shell_argstr, stdout=self._capture) self._echo = return_code_echo_command + command_separator self._interactive = is_interactive self._separator = command_separator self._started = False
def startStreamer(self): if not self._process: command = [ "/mjpeg_streamer/mjpg_streamer", "-i", "input_uvc.so -d %s -f %s -r %s --no_dynctrl%s" % \ (self._device, self._fps, self._size, ' -y' if self._format == 'x-raw' else '' ), "-o", "output_http.so -p %d" % self._httpPort ] self._process = Command( command, env={'LD_LIBRARY_PATH': '/mjpeg_streamer'}, stderr=open(os.devnull, 'w') ) if self._process: self._process.run(async=True) time.sleep(0.2) running = self._process.returncode is None return running return False
def test_command_nonexistent(self): c = Command('nonesuch foo'.split(), stdout=Capture()) if PY3: ARR = self.assertRaisesRegex else: ARR = self.assertRaisesRegexp ARR(ValueError, 'Command not found: nonesuch', c.run)
def get_metadata(self): docker_command = str(self.location) + ' inspect ' + self.imageID p = Command(docker_command, stdout=Capture(buffer_size=-1)) p.run() # Testing directly in the string works if the output is only # one line. # if 'No such image' in p.stdout: # raise DockerImageError # data = [json.loads(str(item)) for item in p.stdout.readline().strip().split('\n')] json_block = [] line = p.stdout.readline() while (line): if 'no such image' in line: raise DockerImageError # Stupid sarge appears to add a blank line between # json statements. This checks for a blank line and # cycles to the next line if it is blank. if re.match(r'^\s*$', line): line = p.stdout.readline() continue json_block.append(line) line = p.stdout.readline() s = ''.join(json_block) s = s[1:-2] self.metadata = s
def remove_image(self, name): """ removes a named image :param name: the name of the image to be removed :return: none """ rm_container_string = str(self.location) + ' rm ' + name rm_container = Command(rm_container_string) rm_container.run()
def stop_container(self, name): """ stops a specified container :param name: name of the container to stop :return:none """ stop_container_string = str(self.location) + ' stop ' + name stop_container = Command(stop_container_string) stop_container.run()
def container_save_as(self, name, saveas, tag): """ Saves a container to a new image :param name: the name of the container to be saved :param saveas: the name of the image to be created :param tag: the tag attached to the new image :return: none """ commit_cmd_string = str( self.location) + ' commit ' + name + ' ' + saveas if tag != "": commit_cmd_string = commit_cmd_string + ':' + tag commit = Command(commit_cmd_string) commit.run()
def test_env_usage(self): if os.name == 'nt': cmd = 'echo %FOO%' else: cmd = 'echo $FOO' if PY3: env = {'FOO': 'BAR'} else: # Python 2.x wants native strings, at least on Windows # (and literals are Unicode in this module) env = {b'FOO': b'BAR'} c = Command(cmd, env=env, stdout=Capture(), shell=True) c.run() self.assertEqual(c.stdout.text.strip(), 'BAR')
def test_env(self): e = os.environ if PY3: env = {'FOO': 'BAR'} else: # Python 2.x wants native strings, at least on Windows # (and literals are Unicode in this module) env = {b'FOO': b'BAR'} c = Command('echo foo', env=env) d = c.kwargs['env'] ek = set(e) dk = set(d) ek.add('FOO') self.assertEqual(dk, ek) self.assertEqual(d['FOO'], 'BAR')
def __init__(self, structure): """ Args: """ self.input_structure = structure.copy() iso_location = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'iso/') self.input_filename_cif = os.path.join(iso_location, 'findsym_input.mcif') self.output_filename_cif = os.path.join(iso_location, 'findsym.cif') # self.input_filename_findsym = os.path.join(iso_location, 'findsym_in.in') self.input_filename_findsym = 'findsym_in.in' self.write_cif_input() # write initial input from mcif file findsym_command = 'findsym_cifinput ' + self.input_filename_cif logger.debug("""starting isotropy session in {} using isotropy in: {}""".format( os.getcwd(), iso_location)) self.findsym_cifinput_process = Command(os.path.join( iso_location, findsym_command), stdout=Capture(buffer_size=1), env={"ISODATA": iso_location}) try: self.findsym_cifinput_process.run(input=PIPE, async_=False) except FileNotFoundError: raise Exception( "Couldn't find Isotropy (findsym) for Linux, see installation instructions" ) with open(self.input_filename_findsym, "w") as io_file: # move past initial output keep_reading = True while keep_reading: # this_line = self.iso_process.stdout.readline().decode() this_line = self.findsym_cifinput_process.stdout.readline( ).decode() if this_line: # don't log until isotropy responds logger.debug("isotropy: {}".format(this_line)) io_file.write(this_line) else: keep_reading = False # run findsym findsym_command = 'findsym ' + self.input_filename_findsym self.findsym_process = Command(os.path.join(iso_location, findsym_command), stdout=Capture(buffer_size=1), env={"ISODATA": iso_location}) try: self.findsym_process.run(input=PIPE, async_=False) except FileNotFoundError: raise Exception( "Couldn't find Isotropy (findsym) for Linux, see installation instructions" ) # # move past initial output # keep_reading = True # while keep_reading: # this_line = self.findsym_process.stdout.readline().decode() # # this_line = self.read_iso_line() # if this_line: # don't log until isotropy responds # logger.debug("isotropy: {}".format(this_line)) # else: # keep_reading = False self.output_cif_file = CifFile.from_file(self.output_filename_cif) msg_int_symbol = int(self.output_cif_file.data['findsym-output']. data['_symmetry_Int_Tables_number']) self.magnetic_space_group = MagneticSpaceGroup(msg_int_symbol)
def __init__(self, values=None, shows=None, labels=None, setting=None): """ Args: values: dictionary of keys to be set to values key is a string specifying what is being set e.g. "basis", "cell", "irrep", "kpoint", "parent" value is what this key is being set to shows: A list of strings corresponding to data which will be returned when display is run. Note: some show commands accept additional parameters, for now these must be included in the string. Eventually parsing of display output should be good enough that they are not needed. labels: NOT YET IMPLEMENTED dictionary where the key corresponds to the object whose notation is being altered, the value corresponds to the new notation to be used for this object for example {"spacegroup": "SCHOENFLIES"} will cause returned results and entered values to use schoenflies notation setting: a string or list of strings to be passed to the setting command can be used to change settings, origin, unique axis and/or cell choice. Can also specify if magnetic spacegroups are desired for now the setting options can only be set when creating an Isotropy object, not changed later """ iso_location = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'iso/') logger.debug("""starting isotropy session in {} using isotropy in: {}""".format( os.getcwd(), iso_location)) self.iso_process = Command(os.path.join(iso_location, 'iso'), stdout=Capture(buffer_size=1), env={"ISODATA": iso_location}) try: self.iso_process.run(input=PIPE, async_=True) except FileNotFoundError: raise Exception( "Couldn't find Isotropy for Linux, see installation instructions" ) # move past initial output keep_reading = True while keep_reading: # this_line = self.iso_process.stdout.readline().decode() this_line = self.read_iso_line() if this_line: # don't log until isotropy responds logger.debug("isotropy: {}".format(this_line)) if this_line == 'Use "VALUE IRREP VERSION" to change version': keep_reading = False self.screen = 999 # exploit this too make parsing output easier? self.sendCommand("SCREEN {}".format(self.screen)) #self.page = "NOBREAK" # still feels the need to periodicly put in labels self.page = "999" self.sendCommand("PAGE {}".format(self.page)) if setting: if type(setting) == list: self.setting = setting else: self.setting = [setting] else: self.setting = ["INTERNATIONAL"] for s in self.setting: self.sendCommand("SETTING {}".format(s)) self.values = Values(self, values) self.shows = Shows(self, shows)
def test_command_run(self): c = Command('echo foo'.split(), stdout=Capture()) c.run() self.assertEqual(c.returncode, 0)
def fileCopyIn(self, dockerlocation, containerid, filename, path): copy_cmd = str( dockerlocation ) + ' cp ' + filename + " " + containerid + ":" + path + filename thisCommand = Command(copy_cmd) thisCommand.run()