简体   繁体   中英

how to get unpredictable directory path with python?

first, I will describe in short the problem I want to solve:

I have a system UNIX based, that running an automatic run that causing images creation.

those images, are saving in a directory that creating during the run and the name of the directory is unpredictable [the name is depends in so many factors and not constant.]

that directory, is created under a constant path, which is:

/usr/local/insight/results/images/toolsDB/lauto_ptest_s + str(datetime.datetime.now()).split()[ 0] + /w1

So, now I got a constant form of path which is a part of my full path. I tried to get the full path in a stupid way:

I wrote a script that open a new terminal by pressing ctrl+alt+sft+w, writing in the terminal the cd command to the constant path, and pressing tab in order to complete the full path [In the constant path there is always one directory that created so pressing tab will always get me the full path].

Theoretically, I have a full path in a terminal, how can I copy this full path and make the function return it?

this is my code:


import pyautogui
import datetime


def open_images_directory():

    pyautogui.hotkey('ctrl', 'alt', 'shift', 'w')
    pyautogui.write(
        'cd' + ' /usr/local/insight/results/images/toolsDB/lauto_ptest_s' + str(datetime.datetime.now()).split()[
            0] + '/w1/')
    pyautogui.sleep(0.5)
    pyautogui.hotkey('tab') # now I have a full path in terminal which I want to return by func


open_images_directory()

Not sure how you use pyautogui for that, but the proper solution would be search the directory structure with some glob patterns

Example:

from pathlib import Path

const_path = Path("const_path")
for path in [p for p in const_path.rglob("*")]:
    if path.is_dir():
        print(f"found directory {path}")
    else:
        print(f"found your image {path}")

const_path.rglob("*") searches every path recursively, (so it will contain every subdirectory), the last one will be your path you are searching for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM