簡體   English   中英

如何在終端中制作 Python 腳本“tab-complete”目錄?

[英]How to make a Python script "tab-complete" directories in terminal?

我有一個 Shell 腳本,比如說run.sh ,它從鍵盤讀取用戶輸入,然后執行一些特定任務。 出於某些技術原因,我將此腳本遷移到 Python,例如run.py ,以實現完全相同的目標。

run.sh文件中,我詢問用戶一個輸入,它通常是文件系統中的一個文件,所以我提供了“tab-completing”它的選項,我只是通過以下行實現它:

read -e -p "Choose a file: " file

-e標志完成選項卡完成用戶輸入的工作。 例如,如果用戶的當前目錄是project ,其結構如下:

project
-- src
-- shared
   -- lib
   -- imgs
      -- image.png
-- include
-- README.txt

並且輸入文件是image.png他們可以如下進行:

sh<tab>i<tab><tab>

結果將是shared/imgs/image.png

現在我如何在 Python 腳本中實現它? 您可能認為有大量相關問題,但我無法在run.py重現完全相同的結果。

到目前為止我嘗試過的:

1. Python 的os模塊:

import os

os.system("read -e -p 'Choose a file:'")

輸出: sh: 1: read: Illegal option -e

2. Python 的subprocess模塊

import subprocess

subprocess.run(['read', '-e', '-p', 'Choose a file'])

輸出:

Traceback (most recent call last):
  File "run.py", line 26, in <module>
    subprocess.run(['read', '-e', '-p', 'Choose a file'])
  File "/usr/lib/python3.7/subprocess.py", line 453, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/lib/python3.7/subprocess.py", line 756, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.7/subprocess.py", line 1499, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'read': 'read'

3. Python 的readline模塊

import readline

readline.parse_and_bind("tab:complete")
file = input("Choose a file: ")

這個看起來幾乎可以工作,但有一個大問題:它只完成用戶當前目錄中的文件。 如果用戶點擊s<tab>然后srcshared出現,但如果他們點擊sh<tab> libimgs目錄不顯示。

我想要一些優雅而簡單的方法來實現這一點,但我相信這可能比預期的要困難一些。 有沒有其他方法可以解決這個問題?

設置合理的完成分隔符:

import readline

readline.set_completer_delims(' \t\n=')
readline.parse_and_bind("tab: complete")
option = input("Tab complete a file: ")

默認情況下, readline將基於以下任何一項進行分隔:

>>> import readline
>>> readline.get_completer_delims()
' \t\n`~!@#$%^&*()-=+[{]}\\|;:\'",<>/?'

由於/是此集合的一部分,因此/之后的任何內容都將獨立於其之前的任何內容完成。 當您嘗試完成文件路徑時,這顯然沒有意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM