I have a Shell Script, let's say run.sh
, which reads a user input from keyboard and then does some specific tasks. For some technical reasons I'm migrating this script to Python, e.g run.py
, in order to achieve the exact same goal.
In the run.sh
file I ask the user a input, which is typically a file in the file system, so I gave the option of "tab-completing" it and I achieved it simply through the line:
read -e -p "Choose a file: " file
The -e
flag does the job of tab-completing users input. For example, if user's current directory is project
, which follows the structure:
project
-- src
-- shared
-- lib
-- imgs
-- image.png
-- include
-- README.txt
and the input file is image.png
they could proceed as follow:
sh<tab>i<tab><tab>
the result would be shared/imgs/image.png
.
Now how do I achieve it inside a Python script? You may believe there are tons of related questions but I haven't been able to reproduce this exact same result in run.py
.
What I have tried so far:
1. Python's os
module:
import os
os.system("read -e -p 'Choose a file:'")
Output: sh: 1: read: Illegal option -e
2. Python's subprocess
module
import subprocess
subprocess.run(['read', '-e', '-p', 'Choose a file'])
Output:
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's readline
module
import readline
readline.parse_and_bind("tab:complete")
file = input("Choose a file: ")
This one almost seems to work, but there is one big issue: it completes only the files in user's current directory. If user hit s<tab>
then src
and shared
show up, but if they hit sh<tab>
the lib
and imgs
directory do not show up.
I'd like some elegant and simple way to achieve this, but I am convinced this might be a little more difficult than expected. Are there any other approaches that can solve this problem?
read
is a shell built-in command, not an actual executable file on disk. (It HAS to be a built-in, because it otherwise couldn't set a shell variable with its result.) – jasonharper May 13 '19 at 20:25