Python os.path.pardir() Examples

The following are 30 code examples for showing how to use os.path.pardir(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module os.path , or try the search function .

Example 1
Project: calmjs   Author: calmjs   File: test_toolchain.py    License: GNU General Public License v2.0 6 votes vote down vote up
def test_toolchain_standard_build_dir_remapped(self):
        """
        This can either be caused by relative paths or symlinks.  Will
        result in the manually specified build_dir being remapped to its
        real location
        """

        fake = mkdtemp(self)
        real = mkdtemp(self)
        real_base = basename(real)
        spec = Spec()
        spec['build_dir'] = join(fake, pardir, real_base)

        with pretty_logging(stream=StringIO()) as s:
            with self.assertRaises(NotImplementedError):
                self.toolchain(spec)

        self.assertIn("realpath of 'build_dir' resolved to", s.getvalue())
        self.assertEqual(spec['build_dir'], real) 
Example 2
Project: weibo-analysis-system   Author: Superbsco   File: tests.py    License: MIT License 6 votes vote down vote up
def getComment(request):
        pass
        # if request.method == "GET":
        # text = request.GET.get("commentId")
        # resp = list(Target.objects.values('uid', 'cookie', 'add_time'))
        # uid = int(resp[0]["uid"])
        # cookie = {"Cookie": resp[0]["cookie"]}
        # wb = Weibo(uid,cookie)
        # print("数据库不存在该评论,正在爬虫生成")
        # mm = wb.get_comment_info(text)


      
# Create your tests here.
# with urllib.request.urlopen("https://wx2.sinaimg.cn/large/" + '893ea4cely1g2kbqkzuzyj21hc0u0q9p', timeout=30) as response, open("893ea4cely1g2kbqkzuzyj21hc0u0q9p.jpg", 'wb') as f_save:
#     f_save.write(response.read())
#     f_save.flush()
#     f_save.close()
# print (path.dirname(path.abspath("__file__")))
# print (path.pardir)
# print (path.join(path.dirname("__file__"),path.pardir))
# print (path.abspath(path.join(path.dirname("__file__"),path.pardir)))
# print (path.abspath(path.join(os.getcwd(), "../../webview/static/"))) 
Example 3
Project: spyder-unittest   Author: spyder-ide   File: unittestgui.py    License: MIT License 6 votes vote down vote up
def test():
    """
    Run widget test.

    Show the unittest widgets, configured so that our own tests are run when
    the user clicks "Run tests".
    """
    from spyder.utils.qthelpers import qapplication
    app = qapplication()
    widget = UnitTestWidget(None)

    # set wdir to .../spyder_unittest
    wdir = osp.abspath(osp.join(osp.dirname(__file__), osp.pardir))
    widget.config = Config('pytest', wdir)

    # add wdir's parent to python path, so that `import spyder_unittest` works
    rootdir = osp.abspath(osp.join(wdir, osp.pardir))
    widget.pythonpath = [rootdir]

    widget.resize(800, 600)
    widget.show()
    sys.exit(app.exec_()) 
Example 4
Project: indra   Author: sorgerlab   File: api.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _load_data():
    """Load the data from the csv in data.

    The "gene_id" is the Entrez gene id, and the "approved_symbol" is the
    standard gene symbol. The "hms_id" is the LINCS ID for the drug.

    Returns
    -------
    data : list[dict]
        A list of dicts of row values keyed by the column headers extracted from
        the csv file, described above.
    """
    # Get the cwv reader object.
    csv_path = path.join(HERE, path.pardir, path.pardir, 'resources',
                         DATAFILE_NAME)
    data_iter = list(read_unicode_csv(csv_path))

    # Get the headers.
    headers = data_iter[0]

    # For some reason this heading is oddly formatted and inconsistent with the
    # rest, or with the usual key-style for dicts.
    headers[headers.index('Approved.Symbol')] = 'approved_symbol'
    return [{header: val for header, val in zip(headers, line)}
            for line in data_iter[1:]] 
Example 5
Project: android-project-combine   Author: Jacksgong   File: res_utils.py    License: Apache License 2.0 6 votes vote down vote up
def find_package_name_dir_up(parent_path):
    for file_name in listdir(parent_path):
        if isdir(file_name):
            continue

        if file_name == 'AndroidManifest.xml':
            for line in open(join(parent_path, file_name), 'r'):
                package_name_re_result = PACKAGE_NAME_RE.search(line)
                if package_name_re_result is not None:
                    return package_name_re_result.groups()[0]

        if file_name == 'build.gradle':
            for line in open(join(parent_path, file_name), 'r'):
                application_id_re_result = APPLICATION_ID_RE.search(line)
                if application_id_re_result is not None:
                    return application_id_re_result.groups()[0]

    return find_package_name_dir_up(abspath(join(parent_path, pardir))) 
Example 6
Project: EvilOSX   Author: Marten4n6   File: gui.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        super(_HomeTab, self).__init__()

        self._layout = QHBoxLayout()
        self.setLayout(self._layout)

        message_label = QLabel("""\
        Welcome to <b>EvilOSX</b>:<br/>
        An evil RAT (Remote Administration Tool) for macOS / OS X.<br/><br/><br/>

        Author: Marten4n6<br/>
        License: GPLv3<br/>
        Version: <b>{}</b>
        """.format(VERSION))
        logo_label = QLabel()

        logo_path = path.join(path.dirname(__file__), path.pardir, path.pardir, "data", "images", "logo_334x600.png")
        logo_label.setPixmap(QPixmap(logo_path))

        self._layout.setAlignment(Qt.AlignCenter)
        self._layout.setSpacing(50)
        self._layout.addWidget(message_label)
        self._layout.addWidget(logo_label) 
Example 7
Project: EvilOSX   Author: Marten4n6   File: model.py    License: GNU General Public License v3.0 6 votes vote down vote up
def wrap_loader(loader_name, loader_options, payload):
        """:return: The loader which will load the (configured and encrypted) payload.

        :type loader_name: str
        :type loader_options: dict
        :type payload: str
        :rtype: str
        """
        loader_path = path.realpath(path.join(
            path.dirname(__file__), path.pardir, "bot", "loaders", loader_name, "install.py")
        )
        loader = ""

        with open(loader_path, "r") as input_file:
            for line in input_file:
                if line.startswith("LOADER_OPTIONS = "):
                    loader += "LOADER_OPTIONS = {}\n".format(str(loader_options))
                elif line.startswith("PAYLOAD_BASE64 = "):
                    loader += "PAYLOAD_BASE64 = \"{}\"\n".format(b64encode(payload.encode()).decode())
                else:
                    loader += line

        return loader 
Example 8
Project: resilient-community-apps   Author: ibmresilient   File: mcafee_esm_case_polling.py    License: MIT License 6 votes vote down vote up
def build_incident_dto(self, headers, case_id):
        current_path = os.path.dirname(os.path.realpath(__file__))
        default_temp_file = join(current_path, pardir, "data/templates/esm_incident_mapping.jinja")
        template_file = self.options.get("incident_template", default_temp_file)

        try:
            with open(template_file, 'r') as template:
                log.debug("Reading template file")

                case_details = case_get_case_detail(self.options, headers, case_id)
                log.debug("Case details in dict form: {}".format(case_details))

                incident_template = template.read()

                return template_functions.render(incident_template, case_details)

        except jinja2.exceptions.TemplateSyntaxError:
            log.info("'incident_template' is not set correctly in config file.") 
Example 9
def build_incident_dto(alert, custom_temp_file=None):
    current_path = os.path.dirname(os.path.realpath(__file__))
    if custom_temp_file:
        template_file = custom_temp_file
    else:
        default_temp_file = join(current_path, pardir, "data/templates/msg_incident_mapping.jinja")
        template_file = default_temp_file

    try:
        with open(template_file, 'r') as template:
            log.debug("Reading template file")
            incident_template = template.read()

            return template_functions.render(incident_template, alert)

    except jinja2.exceptions.TemplateSyntaxError:
        log.info("'incident_template' is not set correctly in config file.") 
Example 10
Project: misp42splunk   Author: remg427   File: loaders.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 11
Project: misp42splunk   Author: remg427   File: loaders.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 12
Project: OP_Manager   Author: adwuard   File: file_util.py    License: MIT License 5 votes vote down vote up
def fileTransferHelper(srclist, dest):
    """
    Pass in list of paths to file, and copy to root destination
    It will create patch's parent folder if not already exist in the destination folder
    For example:
        fileTransferHelper(["..../OP1_File_Organizer/NotUsed/..../patch.aif"], dest = "/..../synth")

    :param srclist: ["pwd/1.aif", "pwd/2.aif", "pwd/3.aif",....., "pwd/n.aif"]
    :param dest: Root of the synth and drum destination folder
    :return: NA
    """

    for i in srclist:
        srcParentFolderName = abspath(join(i, pardir)).split("/")[-1:][0]
        srcBaseName = basename(i)
        distParentFolderName = dest + "/" + str(srcParentFolderName)
        print(distParentFolderName)
        forcedir(distParentFolderName)
        image = Image.new('1', (128, 64))

        if workDir in srclist[0]:
            # Local to OP1
            image.paste(Image.open(workDir + "/Assets/Img/UploadPatches.png").convert("1"))
        else:
            # OP1 to Local
            image.paste(Image.open(workDir + "/Assets/Img/DownloadPatches.png").convert("1"))
        draw = ImageDraw.Draw(image)
        draw.text((20, 63), srcBaseName, font=GPIO_Init.getFont(), fill="white")
        GPIO_Init.displayImage(image)
        print(i, distParentFolderName + "/" + srcBaseName)
        shutil.copy2(i, distParentFolderName + "/" + srcBaseName)

    GPIO_Init.displayPng(workDir + "/Assets/Img/Done.png")
    GPIO_Init.getAnyKeyEvent()  # Press any key to proceed
    return 
Example 13
Project: recruit   Author: Frank-qlu   File: loaders.py    License: Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 14
Project: recruit   Author: Frank-qlu   File: loaders.py    License: Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 15
Project: jbox   Author: jpush   File: loaders.py    License: MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 16
Project: vnpy_crypto   Author: birforce   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_includes():
    """Return a list of directories to include for linking against pyzmq with cython."""
    from os.path import join, dirname, abspath, pardir, exists
    base = dirname(__file__)
    parent = abspath(join(base, pardir))
    includes = [ parent ] + [ join(parent, base, subdir) for subdir in ('utils',) ]
    if exists(join(parent, base, 'include')):
        includes.append(join(parent, base, 'include'))
    return includes 
Example 17
Project: vnpy_crypto   Author: birforce   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_library_dirs():
    """Return a list of directories used to link against pyzmq's bundled libzmq."""
    from os.path import join, dirname, abspath, pardir
    base = dirname(__file__)
    parent = abspath(join(base, pardir))
    return [ join(parent, base) ] 
Example 18
Project: RSSNewsGAE   Author: liantian-cn   File: loaders.py    License: Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 19
Project: Computable   Author: ktraunmueller   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_includes():
    """Return a list of directories to include for linking against pyzmq with cython."""
    from os.path import join, dirname, abspath, pardir
    base = dirname(__file__)
    parent = abspath(join(base, pardir))
    return [ parent ] + [ join(parent, base, subdir) for subdir in ('utils',) ] 
Example 20
Project: pyGISS   Author: afourmy   File: extended_pyGISS.py    License: MIT License 5 votes vote down vote up
def __init__(self, path_app):
        super().__init__()
        self.title('Extended PyGISS')
        path_icon = abspath(join(path_app, pardir, 'images'))
        
        # generate the PSF tk images
        img_psf = ImageTk.Image.open(join(path_icon, 'node.png'))
        selected_img_psf = ImageTk.Image.open(join(path_icon, 'selected_node.png'))
        self.psf_button_image = ImageTk.PhotoImage(img_psf.resize((100, 100)))
        self.node_image = ImageTk.PhotoImage(img_psf.resize((40, 40)))
        self.selected_node_image = ImageTk.PhotoImage(selected_img_psf.resize((40, 40)))

        for widget in (
                       'Button',
                       'Label', 
                       'Labelframe', 
                       'Labelframe.Label', 
                       ):
            ttk.Style().configure('T' + widget, background='#A1DBCD')

        self.map = Map(self)
        self.map.pack(side='right', fill='both', expand=1)

        self.menu = Menu(self)
        self.menu.pack(side='right', fill='both', expand=1)

        menu = tk.Menu(self)
        menu.add_command(label="Import shapefile", command=self.map.import_map)
        self.config(menu=menu)

        # if motion is called, the left-click button was released and we 
        # can stop the drag and drop process
        self.bind_all('<Motion>', self.stop_drag_and_drop)
        self.drag_and_drop = False

        self.image = None
        self.bind_all('<B1-Motion>', lambda _:_) 
Example 21
Project: fbs   Author: mherrmann   File: _source.py    License: GNU General Public License v3.0 5 votes vote down vote up
def default_path(path_str):
    defaults_dir = join(dirname(__file__), pardir, 'fbs', '_defaults')
    return path(defaults_dir, path_str) 
Example 22
Project: fbs   Author: mherrmann   File: _frozen.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_resource_dirs():
    app_dir = dirname(sys.executable)
    return [join(app_dir, pardir, 'Resources') if is_mac() else app_dir] 
Example 23
Project: pipenv   Author: pypa   File: loaders.py    License: MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split("/"):
        if (
            path.sep in piece
            or (path.altsep and path.altsep in piece)
            or piece == path.pardir
        ):
            raise TemplateNotFound(template)
        elif piece and piece != ".":
            pieces.append(piece)
    return pieces 
Example 24
Project: OpenXR-SDK-Source   Author: KhronosGroup   File: loaders.py    License: Apache License 2.0 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 25
Project: timezonefinder   Author: MrMinimal64   File: timezonefinder.py    License: MIT License 5 votes vote down vote up
def __init__(self, bin_file_location: Optional[str] = None, in_memory: bool = False):
        self.in_memory = in_memory

        if self.in_memory:
            self._fromfile = fromfile_memory
        else:
            self._fromfile = fromfile

        # open all the files in binary reading mode
        # for more info on what is stored in which .bin file, please read the comments in file_converter.py
        if bin_file_location is None:
            self.bin_file_location = abspath(join(__file__, pardir))
        else:
            self.bin_file_location = bin_file_location

        for attribute_name in self.binary_data_attributes:
            bin_file = open(join(self.bin_file_location, attribute_name + BINARY_FILE_ENDING), mode='rb')
            if self.in_memory:
                bf_in_mem = BytesIO(bin_file.read())
                bf_in_mem.seek(0)
                bin_file.close()
                bin_file = bf_in_mem
            setattr(self, attribute_name, bin_file)

        with open(join(self.bin_file_location, TIMEZONE_NAMES_FILE), 'r') as json_file:
            setattr(self, TIMEZONE_NAMES, json.loads(json_file.read())) 
Example 26
Project: cheetah-gui   Author: shmilylty   File: cheetah_proxy_support.py    License: GNU General Public License v3.0 5 votes vote down vote up
def save_proxy():
    proxys = w.Scrolledlistbox1.get(0, 'end')
    proxy_path = path.abspath(path.join(path.dirname(__file__), path.pardir, 'data', 'proxy.txt'))
    with open(proxy_path, mode='a') as proxy_file:
        proxy_file.write("\n".join(proxys)) 
Example 27
Project: cheetah-gui   Author: shmilylty   File: cheetah_proxy_support.py    License: GNU General Public License v3.0 5 votes vote down vote up
def save_validated_proxy():
    proxys = w.Scrolledlistbox1.get(0, 'end')
    proxy_path = path.abspath(path.join(path.dirname(__file__), path.pardir, 'data', 'proxy.txt'))
    if path.exists(proxy_path):
        time_stamp = int(time.time())
        proxy_bak_path = '{}.{}.bak'.format(proxy_path, time_stamp)
        rename(proxy_path, proxy_bak_path)
    with open(proxy_path, mode='w') as proxy_file:
        proxy_file.write("\n".join(proxys)) 
Example 28
Project: pySINDy   Author: luckystarufo   File: loaders.py    License: MIT License 5 votes vote down vote up
def split_template_path(template):
    """Split a path into segments and perform a sanity check.  If it detects
    '..' in the path it will raise a `TemplateNotFound` error.
    """
    pieces = []
    for piece in template.split('/'):
        if path.sep in piece \
           or (path.altsep and path.altsep in piece) or \
           piece == path.pardir:
            raise TemplateNotFound(template)
        elif piece and piece != '.':
            pieces.append(piece)
    return pieces 
Example 29
Project: pySINDy   Author: luckystarufo   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_includes():
    """Return a list of directories to include for linking against pyzmq with cython."""
    from os.path import join, dirname, abspath, pardir, exists
    base = dirname(__file__)
    parent = abspath(join(base, pardir))
    includes = [ parent ] + [ join(parent, base, subdir) for subdir in ('utils',) ]
    if exists(join(parent, base, 'include')):
        includes.append(join(parent, base, 'include'))
    return includes 
Example 30
Project: pySINDy   Author: luckystarufo   File: __init__.py    License: MIT License 5 votes vote down vote up
def get_library_dirs():
    """Return a list of directories used to link against pyzmq's bundled libzmq."""
    from os.path import join, dirname, abspath, pardir
    base = dirname(__file__)
    parent = abspath(join(base, pardir))
    return [ join(parent, base) ]