def test_realpath_cwd(self): ABSTFN = ntpath.abspath(support.TESTFN) support.unlink(ABSTFN) support.rmtree(ABSTFN) os.mkdir(ABSTFN) self.addCleanup(support.rmtree, ABSTFN) test_dir_long = ntpath.join(ABSTFN, "MyVeryLongDirectoryName") os.mkdir(test_dir_long) test_dir_short = _getshortpathname(test_dir_long) test_file_long = ntpath.join(test_dir_long, "file.txt") test_file_short = ntpath.join(test_dir_short, "file.txt") with open(test_file_long, "wb") as f: f.write(b"content") self.assertPathEqual(test_file_long, ntpath.realpath(test_file_short)) with support.change_cwd(test_dir_long): self.assertPathEqual(test_file_long, ntpath.realpath("file.txt")) with support.change_cwd(test_dir_long.lower()): self.assertPathEqual(test_file_long, ntpath.realpath("file.txt")) with support.change_cwd(test_dir_short): self.assertPathEqual(test_file_long, ntpath.realpath("file.txt"))
def test_realpath_basic(self): ABSTFN = ntpath.abspath(support.TESTFN) open(ABSTFN, "wb").close() self.addCleanup(support.unlink, ABSTFN) self.addCleanup(support.unlink, ABSTFN + "1") os.symlink(ABSTFN, ABSTFN + "1") self.assertPathEqual(ntpath.realpath(ABSTFN + "1"), ABSTFN) self.assertPathEqual(ntpath.realpath(os.fsencode(ABSTFN + "1")), os.fsencode(ABSTFN))
def testAbsolutifies(self): self.assertPlatformSpecificLogdirParsing( posixpath, "lol/cat", {posixpath.realpath("lol/cat"): None} ) self.assertPlatformSpecificLogdirParsing( ntpath, "lol\\cat", {ntpath.realpath("lol\\cat"): None} )
def create_paintings_db(db_path, data_path): """Creates a list of all paintings in the DB and their info. Parameters ---------- db_path: str path of the directory containing all painting files. data_path: str path of the '.csv' file containing all paintings info. Returns ------- list list of `Painting` objects, describing all the paintings that populate the DB. """ paintings_db = [] try: df_painting_data = pd.read_csv(ntpath.realpath(data_path)) except UnicodeDecodeError: sys.exit(f"Error in the data file format: {data_path}") db_path = ntpath.realpath(db_path) orb = cv2.ORB_create() for subdir, dirs, files in os.walk(db_path): for painting_file in files: image = cv2.imread(os.path.join(db_path, painting_file)) painting_info = df_painting_data.loc[df_painting_data['Image'] == painting_file].iloc[0] title = painting_info['Title'] author = painting_info['Author'] room = painting_info['Room'] # create ORB keypoints and descriptors for each painting in the DB src_kp, src_des = orb.detectAndCompute(image, None) painting = Painting( image, title, author, room, painting_file, keypoints=src_kp, descriptors=src_des ) paintings_db.append(painting) return paintings_db
def test_realpath_relative(self): ABSTFN = ntpath.abspath(support.TESTFN) open(ABSTFN, "wb").close() self.addCleanup(support.unlink, ABSTFN) self.addCleanup(support.unlink, ABSTFN + "1") os.symlink(ABSTFN, ntpath.relpath(ABSTFN + "1")) self.assertPathEqual(ntpath.realpath(ABSTFN + "1"), ABSTFN)
def convert_path(p): p = ntpath.realpath(p) #TODO: not exactly save if '~' in p: p = non83_path(p) drive,path = ntpath.splitdrive(p) drive = drive[0].lower() drive = '/mnt/' + drive path = path.replace('\\', '/') return drive + path
def test_realpath_symlink_prefix(self): ABSTFN = ntpath.abspath(support.TESTFN) self.addCleanup(support.unlink, ABSTFN + "3") self.addCleanup(support.unlink, "\\\\?\\" + ABSTFN + "3.") self.addCleanup(support.unlink, ABSTFN + "3link") self.addCleanup(support.unlink, ABSTFN + "3.link") with open(ABSTFN + "3", "wb") as f: f.write(b'0') os.symlink(ABSTFN + "3", ABSTFN + "3link") with open("\\\\?\\" + ABSTFN + "3.", "wb") as f: f.write(b'1') os.symlink("\\\\?\\" + ABSTFN + "3.", ABSTFN + "3.link") self.assertPathEqual(ntpath.realpath(ABSTFN + "3link"), ABSTFN + "3") self.assertPathEqual(ntpath.realpath(ABSTFN + "3.link"), "\\\\?\\" + ABSTFN + "3.") # Resolved paths should be usable to open target files with open(ntpath.realpath(ABSTFN + "3link"), "rb") as f: self.assertEqual(f.read(), b'0') with open(ntpath.realpath(ABSTFN + "3.link"), "rb") as f: self.assertEqual(f.read(), b'1') # When the prefix is included, it is not stripped self.assertPathEqual(ntpath.realpath("\\\\?\\" + ABSTFN + "3link"), "\\\\?\\" + ABSTFN + "3") self.assertPathEqual(ntpath.realpath("\\\\?\\" + ABSTFN + "3.link"), "\\\\?\\" + ABSTFN + "3.")
def test_realpath_symlink_loops_strict(self): # Symlink loops raise OSError in strict mode ABSTFN = ntpath.abspath(os_helper.TESTFN) self.addCleanup(os_helper.unlink, ABSTFN) self.addCleanup(os_helper.unlink, ABSTFN + "1") self.addCleanup(os_helper.unlink, ABSTFN + "2") self.addCleanup(os_helper.unlink, ABSTFN + "y") self.addCleanup(os_helper.unlink, ABSTFN + "c") self.addCleanup(os_helper.unlink, ABSTFN + "a") os.symlink(ABSTFN, ABSTFN) self.assertRaises(OSError, ntpath.realpath, ABSTFN, strict=True) os.symlink(ABSTFN + "1", ABSTFN + "2") os.symlink(ABSTFN + "2", ABSTFN + "1") self.assertRaises(OSError, ntpath.realpath, ABSTFN + "1", strict=True) self.assertRaises(OSError, ntpath.realpath, ABSTFN + "2", strict=True) self.assertRaises(OSError, ntpath.realpath, ABSTFN + "1\\x", strict=True) # Windows eliminates '..' components before resolving links, so the # following call is not expected to raise. self.assertPathEqual(ntpath.realpath(ABSTFN + "1\\..", strict=True), ntpath.dirname(ABSTFN)) self.assertRaises(OSError, ntpath.realpath, ABSTFN + "1\\..\\x", strict=True) os.symlink(ABSTFN + "x", ABSTFN + "y") self.assertRaises(OSError, ntpath.realpath, ABSTFN + "1\\..\\" + ntpath.basename(ABSTFN) + "y", strict=True) self.assertRaises(OSError, ntpath.realpath, ABSTFN + "1\\..\\" + ntpath.basename(ABSTFN) + "1", strict=True) os.symlink(ntpath.basename(ABSTFN) + "a\\b", ABSTFN + "a") self.assertRaises(OSError, ntpath.realpath, ABSTFN + "a", strict=True) os.symlink( "..\\" + ntpath.basename(ntpath.dirname(ABSTFN)) + "\\" + ntpath.basename(ABSTFN) + "c", ABSTFN + "c") self.assertRaises(OSError, ntpath.realpath, ABSTFN + "c", strict=True) # Test using relative path as well. self.assertRaises(OSError, ntpath.realpath, ntpath.basename(ABSTFN), strict=True)
def unextend_path(self, extended_path): """Remove ClearCase revision and branch information from path. ClearCase paths contain additional information about branch and file version preceded by @@. This function removes these parts from the ClearCase path to make it more readable. For example this function converts the extended path:: /vobs/comm@@/main/122/network@@/main/55/sntp @@/main/4/src@@/main/1/sntp.c@@/main/8 to the the to regular path:: /vobs/comm/network/sntp/src/sntp.c Args: extended_path (unicode): The path to convert. Returns: unicode: The bare filename. """ if '@@' not in extended_path: return HEAD, extended_path # The result of regular expression search is a list of tuples. We must # flatten this to a single list. b is first because it frequently # occurs in tuples. Before that remove @@ from path. unextended_chunks = [ b or a for a, b, foo in self.UNEXTENDED.findall( extended_path.replace('@@', '')) ] if sys.platform.startswith('win'): # Properly handle full (with drive letter) and UNC paths. if unextended_chunks[0].endswith(':'): unextended_chunks[0] = '%s\\' % unextended_chunks[0] elif unextended_chunks[0] == '/' or unextended_chunks[0] == os.sep: unextended_chunks[0] = '\\\\' # Purpose of realpath is remove parts like /./ generated by # ClearCase when vobs branch was fresh created. unextended_path = cpath.realpath(cpath.join(*unextended_chunks)) revision = extended_path.rsplit('@@', 1)[1] if revision.endswith('CHECKEDOUT'): revision = HEAD return (revision, unextended_path)
def unextend_path(self, extended_path): """Remove ClearCase revision and branch informations from path. ClearCase paths contain additional informations about branch and file version preceded by @@. This function remove this parts from ClearCase path to make it more readable For example this function convert extended path:: /vobs/comm@@/main/122/network@@/main/55/sntp @@/main/4/src@@/main/1/sntp.c@@/main/8 to the the to regular path:: /vobs/comm/network/sntp/src/sntp.c """ if '@@' not in extended_path: return HEAD, extended_path # Result of regular expression search result is list of tuples. We must # flat this to one list. The best way is use list comprehension. b is # first because it frequently occure in tuples. Before that remove @@ # from path. unextended_chunks = [ b or a for a, b, foo in self.UNEXTENDED.findall( extended_path.replace('@@', '')) ] if sys.platform.startswith('win'): # Properly handle full (with drive letter) and UNC paths if unextended_chunks[0].endswith(':'): unextended_chunks[0] = '%s\\' % unextended_chunks[0] elif unextended_chunks[0] == '/' or unextended_chunks[0] == os.sep: unextended_chunks[0] = '\\\\' # Purpose of realpath is remove parts like /./ generated by # ClearCase when vobs branch was fresh created unextended_path = cpath.realpath( cpath.join(*unextended_chunks) ) revision = extended_path.rsplit('@@', 1)[1] if revision.endswith('CHECKEDOUT'): revision = HEAD return (revision, unextended_path)
def create_directory(path): """ Create directory at the given path, checking for errors and if the directory already exists. """ path = ntpath.realpath(path) if not os.path.exists(path): try: os.makedirs(path) except Exception as e: print( f"The syntax of the output file name, directory or volume is incorrect: {path}" ) else: print('\n# Created the output directory "{}"'.format(path)) else: print('\n# The output directory "{}" already exists'.format(path))
def unextend_path(self, extended_path): """Remove ClearCase revision and branch informations from path. ClearCase paths contain additional informations about branch and file version preceded by @@. This function remove this parts from ClearCase path to make it more readable For example this function convert extended path:: /vobs/comm@@/main/122/network@@/main/55/sntp @@/main/4/src@@/main/1/sntp.c@@/main/8 to the the to regular path:: /vobs/comm/network/sntp/src/sntp.c """ if not '@@' in extended_path: return HEAD, extended_path # Result of regular expression search result is list of tuples. # We must flat this to one list. The best way is use list comprehension. # b is first because it frequently occure in tuples. # Before that remove @@ from path. unextended_chunks = [ b or a for a, b, foo in self.UNEXTENDED.findall( extended_path.replace('@@', '')) ] if sys.platform.startswith('win'): # Properly handle full (with drive letter) and UNC paths if unextended_chunks[0].endswith(':'): unextended_chunks[0] = '%s\\' % unextended_chunks[0] elif unextended_chunks[0] == '/' or unextended_chunks[0] == os.sep: unextended_chunks[0] = '\\\\' # Purpose of realpath is remove parts like /./ generated by # ClearCase when vobs branch was fresh created unextended_path = cpath.realpath(cpath.join(*unextended_chunks)) revision = extended_path.rsplit('@@', 1)[1] if revision.endswith('CHECKEDOUT'): revision = HEAD return (revision, unextended_path)
def _parse_command_line_options(self): """ Parse the command line options and populate self.args """ self.args = parser.parse_args() # Make the stacks prettier if self.args.stacks: self.args.stacks = [s.strip() for s in self.args.stacks.split(',')] # Split configuration paths if self.args.config: self.args.config = [c.strip() for c in self.args.config.split(',')] if self.args.cumulus_version: settings_conf = SafeConfigParser() settings_conf.read( ospath.realpath( '{}/../settings.conf'.format(ospath.dirname(__file__)))) print('Cumulus version {}'.format( settings_conf.get('general', 'version'))) sys.exit(0) elif not self.args.environment: raise ConfigurationException('--environment is required')
def check_media_file(filename): """Check if the filename is related to a valid image or video. Parameters ---------- filename: str name of the file to check Returns ------- tuple or exit with error if filename is related to a valid media, returns it and its media type (0 = image, 1 = video). Otherwise, it exits with an error message """ media_type = MediaType(0) filename = ntpath.realpath(filename) media = cv2.imread(filename, cv2.IMREAD_COLOR) if media is None: try: media_type = MediaType(1) media = cv2.VideoCapture(filename) if not media.isOpened(): sys.exit( f"The input file should be a valid image or video: '{filename}'\n" ) except cv2.error as e: print("cv2.error:", e) except Exception as e: print("Exception:", e) # else: # print("\n# VIDEO MODE - ON") # else: # print("\n# IMAGE MODE - ON:") return media, media_type
def main(): parser = argparse.ArgumentParser(description="descrizione da mettere") parser.add_argument("--install", help="installa il necessario", action='store_true', default=False, required=False) parser.add_argument("-f", "--file", help="file assembly", type=str, default=None, required=False) parser.add_argument("-nostdlib", help="compila senza stdlib", action='store_true', default=False, required=False) parser.add_argument("-td", help="compilazione a 32 bit", action='store_true', default=False, required=False) parser.add_argument("-mi", "--maxinst", help="numero massimo di istruzioni da simulare (default: 1000)", type=int, default=1000, required=False) parser.add_argument("-fs", "--functionstart", help="funzione da cui iniziare", type=str, default="", required=False) parser.add_argument("-cs", "--ciclestart", help="ciclo da cui iniziare", type=int, default=0, required=False) parser.add_argument("-ce", "--cicleend", help="ciclo con cui terminare", type=int, default=None, required=False) parser.add_argument("-i", "--int", help="valore dei registri intero", action='store_true', default=False, required=False) argms = parser.parse_args() if (argms.install): print("Inizio Installazione") subprocess.run(["sudo", "apt-get", "update"]) subprocess.run(["sudo", "apt-get", "upgrade"]) subprocess.run(["sudo", "apt-get", "install", "mercurial", "scons", "swig", "gcc", "m4", "python", "python-dev", "libgoogle-perftools-dev", "g++", "python3", "python3-pip", "python-pip", "libc6-armel-cross", "libc6-dev-armel-cross", "binutils-arm-linux-gnueabi", "libncurses5-dev", "gcc-arm-linux-gnueabihf", "gcc-aarch64-linux-gnu", "g++-arm-linux-gnueabihf", "git-core", "libboost-dev", "zlib1g-dev"]) subprocess.run(["pip3", "install", "argparse", "six", "capstone"]) subprocess.run(["pip", "install", "argparse", "six", "capstone"]) subprocess.run(["git", "clone", "https://github.com/gem5/gem5.git"]) subprocess.run(["scons", "build/ARM/gem5.debug", "-j4"],cwd='gem5') subprocess.run([sys.argv[0], "-f", "Programmi/test.s", "-nostdlib", "-mi", "100", "-fs", "_start", "-td"]) print("Fine Installazione") elif not(argms.file is None): path = ntpath.realpath(argms.file) path=path.replace('\\', '/') filename = ntpath.basename(argms.file) pathobject = path+".o" if os.path.exists(pathobject): os.remove(pathobject) traceoutfile = filename+".trace" traceoutfilepath = 'm5out/'+traceoutfile if os.path.exists(traceoutfilepath): os.remove(traceoutfilepath) visualtrace = filename+".out" if os.path.exists(visualtrace): os.remove(visualtrace) maxinst = str(argms.maxinst) visualarray = ["./dumptohuman.py", "-f", traceoutfilepath, "-cs", str(argms.ciclestart)] if argms.functionstart != '': visualarray.insert(3, argms.functionstart) visualarray.insert(3, "-fs") if not(argms.cicleend is None): visualarray.insert(3, str(argms.cicleend)) visualarray.insert(3, "-ce") if argms.int: visualarray.insert(3, "-i") if argms.td : visualarray.insert(3, "-td") visualtracefile = open(visualtrace, "w") nullfile = open("/dev/null","w") print('Inizio compilazione') if not argms.td : if argms.nostdlib : subprocess.run(["aarch64-linux-gnu-gcc", "-nostdlib", "-march=armv8-a", "--static", "-o", pathobject, path]) else: subprocess.run(["aarch64-linux-gnu-gcc", "--static", "-march=armv8-a", "-o", pathobject, path]) else: if argms.nostdlib : subprocess.run(["arm-linux-gnueabihf-gcc", "-nostdlib", "-mcpu=cortex-a7", "--static", "-o", pathobject, path]) else: subprocess.run(["arm-linux-gnueabihf-gcc", "--static", "-mcpu=cortex-a7", "-o", pathobject, path]) if not os.path.exists(pathobject): print('Compilazione fallita') sys.exit() print('Fine compilazione') time.sleep(1) print('Inizio Simulazione') subprocess.run(["gem5/build/ARM/gem5.debug", "--debug-flags=All", "--debug-file="+traceoutfile, "--debug-start=0", "gem5/configs/example/se.py", "--maxinst="+maxinst, "--cpu-type=MinorCPU", "--caches", "-c", pathobject], stderr=nullfile) if not os.path.exists(traceoutfilepath): print('Simulazione fallita') sys.exit() subprocess.run(visualarray, stdout=visualtracefile) print('dumped on '+visualtrace) print('Fine Simulazione') visualtracefile.close() nullfile.close() else: parser.print_help() sys.exit()
def test_realpath_symlink_loops(self): # Symlink loops are non-deterministic as to which path is returned, but # it will always be the fully resolved path of one member of the cycle ABSTFN = ntpath.abspath(support.TESTFN) self.addCleanup(support.unlink, ABSTFN) self.addCleanup(support.unlink, ABSTFN + "1") self.addCleanup(support.unlink, ABSTFN + "2") self.addCleanup(support.unlink, ABSTFN + "y") self.addCleanup(support.unlink, ABSTFN + "c") self.addCleanup(support.unlink, ABSTFN + "a") os.symlink(ABSTFN, ABSTFN) self.assertPathEqual(ntpath.realpath(ABSTFN), ABSTFN) os.symlink(ABSTFN + "1", ABSTFN + "2") os.symlink(ABSTFN + "2", ABSTFN + "1") expected = (ABSTFN + "1", ABSTFN + "2") self.assertPathIn(ntpath.realpath(ABSTFN + "1"), expected) self.assertPathIn(ntpath.realpath(ABSTFN + "2"), expected) self.assertPathIn(ntpath.realpath(ABSTFN + "1\\x"), (ntpath.join(r, "x") for r in expected)) self.assertPathEqual(ntpath.realpath(ABSTFN + "1\\.."), ntpath.dirname(ABSTFN)) self.assertPathEqual(ntpath.realpath(ABSTFN + "1\\..\\x"), ntpath.dirname(ABSTFN) + "\\x") os.symlink(ABSTFN + "x", ABSTFN + "y") self.assertPathEqual(ntpath.realpath(ABSTFN + "1\\..\\" + ntpath.basename(ABSTFN) + "y"), ABSTFN + "x") self.assertPathIn(ntpath.realpath(ABSTFN + "1\\..\\" + ntpath.basename(ABSTFN) + "1"), expected) os.symlink(ntpath.basename(ABSTFN) + "a\\b", ABSTFN + "a") self.assertPathEqual(ntpath.realpath(ABSTFN + "a"), ABSTFN + "a") os.symlink("..\\" + ntpath.basename(ntpath.dirname(ABSTFN)) + "\\" + ntpath.basename(ABSTFN) + "c", ABSTFN + "c") self.assertPathEqual(ntpath.realpath(ABSTFN + "c"), ABSTFN + "c") # Test using relative path as well. self.assertPathEqual(ntpath.realpath(ntpath.basename(ABSTFN)), ABSTFN)
def test_realpath_broken_symlinks(self): ABSTFN = ntpath.abspath(support.TESTFN) os.mkdir(ABSTFN) self.addCleanup(support.rmtree, ABSTFN) with support.change_cwd(ABSTFN): os.mkdir("subdir") os.chdir("subdir") os.symlink(".", "recursive") os.symlink("..", "parent") os.chdir("..") os.symlink(".", "self") os.symlink("missing", "broken") os.symlink(r"broken\bar", "broken1") os.symlink(r"self\self\broken", "broken2") os.symlink(r"subdir\parent\subdir\parent\broken", "broken3") os.symlink(ABSTFN + r"\broken", "broken4") os.symlink(r"recursive\..\broken", "broken5") self.assertPathEqual(ntpath.realpath("broken"), ABSTFN + r"\missing") self.assertPathEqual(ntpath.realpath(r"broken\foo"), ABSTFN + r"\missing\foo") # bpo-38453: We no longer recursively resolve segments of relative # symlinks that the OS cannot resolve. self.assertPathEqual(ntpath.realpath(r"broken1"), ABSTFN + r"\broken\bar") self.assertPathEqual(ntpath.realpath(r"broken1\baz"), ABSTFN + r"\broken\bar\baz") self.assertPathEqual(ntpath.realpath("broken2"), ABSTFN + r"\self\self\missing") self.assertPathEqual(ntpath.realpath("broken3"), ABSTFN + r"\subdir\parent\subdir\parent\missing") self.assertPathEqual(ntpath.realpath("broken4"), ABSTFN + r"\missing") self.assertPathEqual(ntpath.realpath("broken5"), ABSTFN + r"\missing") self.assertPathEqual(ntpath.realpath(b"broken"), os.fsencode(ABSTFN + r"\missing")) self.assertPathEqual(ntpath.realpath(rb"broken\foo"), os.fsencode(ABSTFN + r"\missing\foo")) self.assertPathEqual(ntpath.realpath(rb"broken1"), os.fsencode(ABSTFN + r"\broken\bar")) self.assertPathEqual(ntpath.realpath(rb"broken1\baz"), os.fsencode(ABSTFN + r"\broken\bar\baz")) self.assertPathEqual(ntpath.realpath(b"broken2"), os.fsencode(ABSTFN + r"\self\self\missing")) self.assertPathEqual(ntpath.realpath(rb"broken3"), os.fsencode(ABSTFN + r"\subdir\parent\subdir\parent\missing")) self.assertPathEqual(ntpath.realpath(b"broken4"), os.fsencode(ABSTFN + r"\missing")) self.assertPathEqual(ntpath.realpath(b"broken5"), os.fsencode(ABSTFN + r"\missing"))
def update_event(self, inp=-1): self.set_output_val(0, ntpath.realpath(self.input(0)))
def test_realpath_symlink_loops(self): # Bug #930024, return the path unchanged if we get into an infinite # symlink loop. ABSTFN = ntpath.abspath(support.TESTFN) self.addCleanup(support.unlink, ABSTFN) self.addCleanup(support.unlink, ABSTFN + "1") self.addCleanup(support.unlink, ABSTFN + "2") self.addCleanup(support.unlink, ABSTFN + "y") self.addCleanup(support.unlink, ABSTFN + "c") self.addCleanup(support.unlink, ABSTFN + "a") P = "\\\\?\\" os.symlink(ABSTFN, ABSTFN) self.assertEqual(ntpath.realpath(ABSTFN), P + ABSTFN) # cycles are non-deterministic as to which path is returned, but # it will always be the fully resolved path of one member of the cycle os.symlink(ABSTFN + "1", ABSTFN + "2") os.symlink(ABSTFN + "2", ABSTFN + "1") expected = (P + ABSTFN + "1", P + ABSTFN + "2") self.assertIn(ntpath.realpath(ABSTFN + "1"), expected) self.assertIn(ntpath.realpath(ABSTFN + "2"), expected) self.assertIn(ntpath.realpath(ABSTFN + "1\\x"), (ntpath.join(r, "x") for r in expected)) self.assertEqual(ntpath.realpath(ABSTFN + "1\\.."), ntpath.dirname(ABSTFN)) self.assertEqual(ntpath.realpath(ABSTFN + "1\\..\\x"), ntpath.dirname(ABSTFN) + "\\x") os.symlink(ABSTFN + "x", ABSTFN + "y") self.assertEqual( ntpath.realpath(ABSTFN + "1\\..\\" + ntpath.basename(ABSTFN) + "y"), ABSTFN + "x") self.assertIn( ntpath.realpath(ABSTFN + "1\\..\\" + ntpath.basename(ABSTFN) + "1"), expected) os.symlink(ntpath.basename(ABSTFN) + "a\\b", ABSTFN + "a") self.assertEqual(ntpath.realpath(ABSTFN + "a"), P + ABSTFN + "a") os.symlink( "..\\" + ntpath.basename(ntpath.dirname(ABSTFN)) + "\\" + ntpath.basename(ABSTFN) + "c", ABSTFN + "c") self.assertEqual(ntpath.realpath(ABSTFN + "c"), P + ABSTFN + "c") # Test using relative path as well. self.assertEqual(ntpath.realpath(ntpath.basename(ABSTFN)), P + ABSTFN)
def test_realpath_broken_symlinks(self): ABSTFN = ntpath.abspath(support.TESTFN) os.mkdir(ABSTFN) self.addCleanup(support.rmtree, ABSTFN) with support.change_cwd(ABSTFN): os.mkdir("subdir") os.chdir("subdir") os.symlink(".", "recursive") os.symlink("..", "parent") os.chdir("..") os.symlink(".", "self") os.symlink("missing", "broken") os.symlink(r"broken\bar", "broken1") os.symlink(r"self\self\broken", "broken2") os.symlink(r"subdir\parent\subdir\parent\broken", "broken3") os.symlink(ABSTFN + r"\broken", "broken4") os.symlink(r"recursive\..\broken", "broken5") self.assertEqual(ntpath.realpath("broken"), ABSTFN + r"\missing") self.assertEqual(ntpath.realpath(r"broken\foo"), ABSTFN + r"\missing\foo") self.assertEqual(ntpath.realpath(r"broken1"), ABSTFN + r"\missing\bar") self.assertEqual(ntpath.realpath(r"broken1\baz"), ABSTFN + r"\missing\bar\baz") self.assertEqual(ntpath.realpath("broken2"), ABSTFN + r"\missing") self.assertEqual(ntpath.realpath("broken3"), ABSTFN + r"\missing") self.assertEqual(ntpath.realpath("broken4"), ABSTFN + r"\missing") self.assertEqual(ntpath.realpath("broken5"), ABSTFN + r"\missing") self.assertEqual(ntpath.realpath(b"broken"), os.fsencode(ABSTFN + r"\missing")) self.assertEqual(ntpath.realpath(rb"broken\foo"), os.fsencode(ABSTFN + r"\missing\foo")) self.assertEqual(ntpath.realpath(rb"broken1"), os.fsencode(ABSTFN + r"\missing\bar")) self.assertEqual(ntpath.realpath(rb"broken1\baz"), os.fsencode(ABSTFN + r"\missing\bar\baz")) self.assertEqual(ntpath.realpath(b"broken2"), os.fsencode(ABSTFN + r"\missing")) self.assertEqual(ntpath.realpath(rb"broken3"), os.fsencode(ABSTFN + r"\missing")) self.assertEqual(ntpath.realpath(b"broken4"), os.fsencode(ABSTFN + r"\missing")) self.assertEqual(ntpath.realpath(b"broken5"), os.fsencode(ABSTFN + r"\missing"))
import random if sys.platform in ['win32', 'cygwin']: import ntpath as ospath else: import os.path as ospath from netaddr import IPNetwork, AddrFormatError, AddrConversionError from ec2_metadata import ec2_metadata import boto3 from aws_ec2_assign_elastic_ip.command_line_options import ARGS as args logging.config.fileConfig('{0}/logging.conf'.format( ospath.dirname(ospath.realpath(__file__)))) logger = logging.getLogger('aws-ec2-assign-eip') region = args.region try: region = ec2_metadata.region except KeyError: pass # Connect to AWS EC2 if args.access_key or args.secret_key: # Use command line credentials connection = boto3.client('ec2', region_name=region,
def testAbsolutifies(self): self.assertPlatformSpecificLogdirParsing( posixpath, 'lol/cat', {posixpath.realpath('lol/cat'): None}) self.assertPlatformSpecificLogdirParsing( ntpath, 'lol\\cat', {ntpath.realpath('lol\\cat'): None})
if sys.platform in ['win32', 'cygwin']: import ntpath as ospath else: import os.path as ospath import boto.utils from netaddr import IPNetwork, AddrFormatError, AddrConversionError from boto.ec2 import connect_to_region from boto.utils import get_instance_metadata from aws_ec2_assign_elastic_ip.command_line_options import ARGS as args logging.config.fileConfig('{0}/logging.conf'.format( ospath.dirname(ospath.realpath(__file__)))) logger = logging.getLogger('aws-ec2-assign-eip') region = args.region # Fetch instance metadata metadata = get_instance_metadata(timeout=1, num_retries=1) if metadata: try: region = metadata['placement']['availability-zone'][:-1] except KeyError: pass # Connect to AWS EC2 if args.access_key or args.secret_key: