简体   繁体   English

如何使用 python 获取不可预测的目录路径?

[英]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.我有一个基于 UNIX 的系统,它运行导致图像创建的自动运行。

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 /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].我编写了一个脚本,通过按 ctrl+alt+sft+w 打开一个新终端,在终端中将 cd 命令写入常量路径,然后按 Tab 以完成完整路径 [在常量路径中总是有一个创建的目录,因此按选项卡将始终让我获得完整路径]。

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不确定您如何使用pyautogui ,但正确的解决方案是使用一些glob 模式搜索目录结构

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. const_path.rglob("*")递归搜索每个路径(因此它将包含每个子目录),最后一个将是您要搜索的路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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