简体   繁体   English

Python Shell脚本

[英]Python Shell Script

I'm trying to understand some basic shell scripting. 我试图了解一些基本的shell脚本。 I have a script.sh , did the chmod, and was messing around with some pretty easy print statements by executing ./script.sh 我有一个script.sh ,执行了chmod,并且通过执行./script.sh弄乱了一些非常简单的打印语句

Now how could I launch the shell displaying a prompt that includes the current working directory, and said prompt should accept a line of input and display a prompt each time? 现在,我如何启动显示包含当前工作目录的提示的外壳程序,并且该提示应接受一行输入并每次显示一个提示?

To sum up the tools I understand so far: os.getcwd() , sys.stdin.readlines() , subprocess.Popen(['ls'], stdout=subproccess.PIPE) 总结到目前为止我了解的工具: os.getcwd()sys.stdin.readlines()sys.stdin.readlines() subprocess.Popen(['ls'], stdout=subproccess.PIPE)

Here is what I have so far. 这是我到目前为止所拥有的。

#!/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()

So this seems to work. 因此,这似乎可行。 At least the command prompt part, not exiting. 至少在命令提示符下没有退出。

If you want to prompt the user, then you probably don't want to be using sys.stdin.readlines() as there isn't really an easy way to put your prompt in after each line. 如果要提示用户,则可能不想使用sys.stdin.readlines()因为实际上没有一种简单的方法可以在每行之后添加提示。 Instead, use input() (or raw_input() on Python 2). 相反,请使用input() (或在Python 2上使用raw_input() )。

user_input = input("My prompt text> ")

Then the user's input will be stored in a string in user_input . 然后,用户的输入将存储在user_input中的字符串中。 Put that in a while loop, and you can have it repeatedly display, like a regular command prompt. 将其放在while循环中,就可以像常规命令提示符一样反复显示它。

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

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