我正在尝试了解一些基本的 shell 脚本。我有一个 script.sh
,执行了 chmod,并通过执行 ./script.sh 搞乱了一些非常简单的打印语句
现在我如何启动 shell 显示包含当前工作目录的提示,并且提示应该接受一行输入并每次都显示提示?
总结一下我目前理解的工具:os.getcwd()
, sys.stdin.readlines()
, subprocess.Popen([' ls'], stdout=subproccess.PIPE)
这是我目前所拥有的。
#!/usr/bin/env python
import os
import sys
import subprocess
proc = subprocess.Popen(['ls'], stdout=subprocess.PIPE)
cwd = os.getcwd()
while True:
user_input = raw_input(str(cwd) + " >> ")
if user_input == 'ls':
print proc
if not foo:
sys.exit()
所以这似乎可行。至少命令提示符部分,不退出。
最佳答案
如果你想提示用户,那么你可能不想使用 sys.stdin.readlines()
因为没有一个简单的方法可以在之后输入提示每行。相反,请使用 input()
(或在 Python 2 上使用 raw_input()
)。
user_input = input("My prompt text> ")
然后用户的输入将以字符串的形式存储在user_input
中。将它放在 while 循环中,您可以让它重复显示,就像常规命令提示符一样。
关于Python shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40923557/