如何在 Windows CMD 树命令中附加尾部斜杠?

如何在 Windows CMD 树命令中附加尾部斜杠?

在 Windows CMD 中执行该tree命令将会给我一些如下输出:

C:\DIR1
│   foo.txt
└───dir2
        bar.txt

如何在目录后面附加斜杠以使其更清楚地表明它们不是文件?它应该适用于根目录和子目录,如下所示:

C:\DIR1\
│   foo.txt
└───dir2\
        bar.txt

答案1

概述

一个解决方案是使用Python脚本来包装命令并以此方式在每个目录的末尾tree添加尾随。\

以下脚本适用于 Python 3.x。如果您决定使用此脚本,您可能需要在命令行中安装 Python 以方便使用,并将.py文件与 Python 关联。


注意事项

  • 包装tree命令会使它稍微慢一些(由于脚本执行时间)。也就是说,这种差异可能很小,在大多数情况下可以忽略不计。

  • 我们已尽最大努力tree尽可能真实地重现 的输出(因此,tree除了添加 之外, 和 此脚本之间实际上应该没有区别\)。但是,理论上您可能会遇到一些未知的输出问题,具体取决于您的用例。

  • 您可能会遇到的一个问题是输出到文本文件。如果/A未指定,此脚本将崩溃。tree更优雅的是它只是写入“错误”的字符。

  • 可能出现的一个小问题是,当使用 ASCII( )输出模式时,从技术上讲,任何包含+---作为其名称一部分的项目(假设该项目不是目录)都有可能出现“误报” 。/A

  • 如果为变量指定完整路径(如下),则使用\\(而不仅仅是)。\root_dir

  • /F命令行中的实现/A是有意简化的。如果您想要更强大的功能,您应该查看参数解析(或者直接阅读tree /?)。

  • 此脚本是针对 Windows 7 和代码页编写的cp1252cp437您可能需要根据您居住的地方等更改这些编码值。


脚本

笔记

tree运行时,它使用三个扩展管道符号 ( ───) 或三个连字符 ( ---) 作为目录名称的前缀。此脚本查找包含这些值的行,并\根据需要将其添加到这些行的末尾。

您可以使用初始show_files和值设置默认脚本选项。命令行ascii_tree选项可以分别是bonsai.pybonsai.py /F或。bonsai.py /Abonsai.py /F /A

如上所述,root_dir它被硬编码到脚本中(即,它没有可以从命令行设置的选项)。

例如 bonsai.py

# Wrapper for the Windows "tree" command, which adds a "\" to the end of
# directory names to more easily distinguish them from files.

# https://docs.python.org/3/library/subprocess.html
# https://docs.python.org/3/library/sys.html

# --- Imports ---

import subprocess
import sys

# --- Switches ---

# Select "tree" "/F" and "/A" options. "/F" displays files under directory
# listings and "/A" controls ASCII output (i.e. no extended characters).

# These should only ever be "True" or "False".
show_files = False
ascii_tree = False

# Command line options
if '/F' in sys.argv:
    show_files = True

if '/A' in sys.argv:
    ascii_tree = True

options = ''

if show_files is True:
    options += ' /F'

if ascii_tree is True:
    options += ' /A'

# --- Variables ---

# Tree the current local directory.
root_dir = '.'

# --- Main ---

# Define our subprocess.run() command.

# Tree the current local directory
# command = 'cmd /c tree'

# Optional
command = 'cmd /c tree' + ' ' + root_dir + options

# Visual aid
# print('')

# Run our subprocess.run() command and capture its output.
# raw_output is subprocess.CompletedProcess object.
raw_output = subprocess.run(command, capture_output=True)

# "temp_output" is a bytes() object of the text produced by "tree".
temp_output = raw_output.stdout

# Clean up whatever text was produced by "tree" at the command line.
# Turn "temp_output" into a decoded string (from a bytes() object).
# Code Page 437 should represent any extended symbols correctly.
text_output = temp_output.decode('cp437')

# Used for extended output
if ascii_tree is False:

    # Build our (pipe) symbols variable required for directory matching.
    dir_prefix = bytes('\xc4\xc4\xc4', 'cp1252')
    decoded_prefix = dir_prefix.decode('cp437')

# Used for ASCII output
if ascii_tree is True:

    # Build our (hyphen, etc.) symbols variables for directory matching.
    dir_prefix_ascii_A = '+---'
    dir_prefix_ascii_B = '\\---'

# Build a list holding our "tree" command output.
# We can use string.split('\r\n') because we use e.g. "cp437" for decoding.
tree_list = text_output.split('\r\n')

# Process our tree_list[]. Add a "\" to any line that is a directory.
for line in tree_list:

    # Copy our current tree_list[] line
    entry = line

    # Replace any eight digit random numbers and ":" in our "Volume"
    # information. These are apparently side-effects of this script.
    if line.startswith('Volume'):

        # Our eight digit random number in front of the "Volume" ID apparently
        # has a constant position (in line 2). Therefore, we make a list of the
        # words in that line and remove the correct element in that word list,
        # then reconstruct the line.

        # Make our word list
        words = entry.split()

        # Remove our random eight digit number. "del words[4]" would work as
        # well (with no element returned).
        random_number = words.pop(4)

        # Accounts for lists starting at 0 and lengths starting at 1.
        words_max = len(words) - 1

        # Get the string value of the word in our last words[] element.
        last_word = words[words_max]

        # Blanking is done *after* we have copied our entry line to words[].
        entry = ''

        # Reconstruct our current line (sans our "random_number").
        for word in words:
            if word is not last_word:
                entry += word + ' '
            else:
                entry += word

        # Replace ":" with "-", as output by the "tree" command.
        entry = entry.replace(':', '-')

    # Add a trailing slash to our root directory, including "." (e.g. "C:.\")
    if ':\\' in line or ':.' in line:
        entry += '\\'

    # Used for extended output
    if ascii_tree is False:

        # Check if our "decoded_prefix" i.e. extended pipe characters
        # are in the given line (indicating a directory).
        if decoded_prefix in line:

            # If so, add a trailing slash "\"
            entry += '\\'

    # Used for ASCII output
    if ascii_tree is True:

        # Check if "dir_prefix_ascii_A" or "dir_prefix_ascii_B" i.e. ASCII
        # "+---" or "\---" are in the given line (indicating a directory).
        if dir_prefix_ascii_A in line or dir_prefix_ascii_B in line:

            # If so, add a trailing slash "\"
            entry += '\\'

    # Display our final (modified) tree line.
    # Corrects for a final blank line in our tree_list[].
    if entry != '':
        print(entry)

相关内容