使用 Python 创建终端程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17352630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a Terminal Program with Python
提问by Niels
I recently started learning python. I have created some basic webapps with Django and wrote some simple scripts. After using VIM as a Python IDE I really fell I love with "Terminal programs" (is there an official term for this?). Right now I am capable of doing simple things like asking someones age and printing it to the screen. However this comes down to running a .py script and after this script is done the normal bash return. I would like create a program that I can run from the command line and that would allow the same user experience as VIM (one that you open and close). For example I created a simple script to import RSS feeds. It would be cool if I could open my terminal type the name of my program -> program would open -> Then I would like to use commands like :findsomething. Basically have real interaction with my program.
我最近开始学习python。我用 Django 创建了一些基本的 web 应用程序并编写了一些简单的脚本。在使用 VIM 作为 Python IDE 之后,我真的爱上了“终端程序”(有官方术语吗?)。现在我能够做一些简单的事情,比如询问某人的年龄并将其打印到屏幕上。然而,这归结为运行一个 .py 脚本,在这个脚本完成后,正常的 bash 返回。我想创建一个可以从命令行运行的程序,它可以提供与 VIM 相同的用户体验(您可以打开和关闭)。例如,我创建了一个简单的脚本来导入 RSS 提要。如果我可以打开我的终端输入我的程序名称 -> 程序将打开 -> 然后我想使用像 :findsomething 这样的命令,那就太酷了。
To conclude:
总结:
- How would I go about creating such a program?
- What kinds of modules, books or site would you recommend
- 我将如何着手创建这样一个程序?
- 您会推荐哪些类型的模块、书籍或网站
采纳答案by user4815162342
A true command-line program is something in the vein of ls
or grep
; it is started from the command-line, but it's non-interactive and can be used in pipelines and combined with other programs. A typical command-line program has no interactive user experience, instead relying on shell's history and init file for customization.
一个真正的命令行程序是类似于ls
or 的东西grep
;它从命令行启动,但它是非交互式的,可以在管道中使用并与其他程序结合使用。典型的命令行程序没有交互式用户体验,而是依靠 shell 的历史记录和 init 文件进行自定义。
What you want to create is a cursesapplication, that uses the full capabilities of the TTY as an interactive platform, for better or worse. To do that, look up curses.
您想要创建的是一个curses应用程序,它使用TTY 的全部功能作为交互式平台,无论好坏。为此,请查找curses。
回答by Brien
回答by MJ Howard
THe simplest way to do an interactive console application would be:
执行交互式控制台应用程序的最简单方法是:
while True:
command = raw_input('command? ').strip()
if command == 'say_hello':
print('Hello')
elif command == 'other_thing':
print('Doing something else')
elif command == 'quit':
break
else:
print('Invalid Command.')
That's the basic structure. If you want something more vim-like, you'll probably need to use the curses library.
这就是基本结构。如果你想要更像 vim 的东西,你可能需要使用 curses 库。
回答by Noctis Skytower
You should take a look at the cmdmodule.
你应该看看cmd模块。
See the Python Cookbookfor examples of its use.
有关其使用示例,请参阅Python Cookbook。
回答by ox.
On a *nix system (linux/unix),
if you:
在 *nix 系统 (linux/unix) 上,
如果您:
$ chmod 0744 your_file.py
-rwxr--r-- your_file.py
and add the path to python as the first line of your_file.py
:
并将python的路径添加为以下内容的第一行your_file.py
:
#!/usr/bin/python
or (in my case):
或(就我而言):
#!/usr/local/bin/python
Once you do that, instead of running it like this:
一旦你这样做了,而不是像这样运行它:
$ python your_file.py
You can run it like this:
你可以像这样运行它:
$ ./your_file.py
or even rename it to yourfile
and run it like this:
或者甚至将它重命名为yourfile
并像这样运行它:
$ ./yourfile
and if you then copy yourfile
to your bin (i.e. #!/usr/bin/
, or #!/usr/local/bin/
)
you can run it like this:
如果您然后复制yourfile
到您的 bin(即#!/usr/bin/
, 或#!/usr/local/bin/
),您可以像这样运行它:
$ yourfile
Then you can...
然后你可以...
Use raw_input()
to solicit and get input from you user.
使用raw_input()
征求和你的用户得到输入。
your_file.py
:
your_file.py
:
#!/usr/local/bin/python
import os
while(True):
# cntrl-c to quit
input = raw_input('your_prompt$ ')
input = input.split()
if input[0] == 'ls':
dire = '.'
if len(input) > 1:
dire = input[1]
print('\n'.join(os.listdir(dire)))
else:
print('error')
your_file.py
use example:
your_file.py
使用示例:
$ chmod 744 your_file.py
$ cp your_file.py /usr/local/bin/your_file
$ your_file
your_prompt$ ls
list_argv.py
your_file.py
your_ls.py
your_subprocess.py
your_prompt$ ls .
list_argv.py
your_file.py
your_ls.py
your_subprocess.py
your_prompt$ pwd
error
your_prompt$ ^CTraceback (most recent call last):
File "/usr/local/bin/your_file", line 7, in <module>
input = raw_input('your_prompt$ ')
KeyboardInterrupt
$
Grab arguments with sys.argv
from the command line when you run your script:
sys.argv
运行脚本时从命令行获取参数:
list_argv.py
:
list_argv.py
:
#!/usr/local/bin/python
import sys
print(sys.argv)
list_argv.py
use example:
list_argv.py
使用示例:
$ python list_argv.py
['list_argv.py']
$ python list_argv.py hello
['list_argv.py', 'hello']
$ python list_argv.py hey yo
['list_argv.py', 'hey', 'yo']
$ chmod 744 list_argv.py
$ ./list_argv.py
['./list_argv.py']
$ ./list_argv.py hi
['./list_argv.py', 'hi']
$ ./list_argv.py hey yo
['./list_argv.py', 'hey', 'yo']
$ cp list_argv.py /usr/local/bin/list_argv
$ list_argv hey yo
['/usr/local/bin/list_argv', 'hey', 'yo']
Replace raw_input()
with sys.argv
.
替换raw_input()
为sys.argv
。
'your_ls.py':
'your_ls.py':
#!/usr/local/bin/python
import sys
import os
dire = '.'
if len(sys.argv) > 1:
dire = sys.argv[1]
print('\n'.join(os.listdir(dire)))
'your_ls.py' use example:
'your_ls.py' 使用示例:
$ chmod 744 your_ls.py
$ cp your_ls.py /usr/local/bin/your_ls
$ your_ls
list_argv.py
your_file.py
your_ls.py
your_subprocess.py
$ your_ls .
list_argv.py
your_file.py
your_ls.py
your_subprocess.py
$ your_ls blah
Traceback (most recent call last):
File "/usr/local/bin/your_ls", line 9, in <module>
print('\n'.join(os.listdir(dire)))
OSError: [Errno 2] No such file or directory: 'blah'
Use subprocess.Popen
to access anything you could from the command line.
用于subprocess.Popen
从命令行访问任何可以访问的内容。
your_subprocess.py
:
your_subprocess.py
:
#!/usr/local/bin/python
import os
import subprocess
while(True):
# cntrl-c to quit
input = raw_input('your_prompt$ ')
process = subprocess.Popen(input, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = process.communicate()
print(out)
print(err)
your_subprocess.py
use example:
your_subprocess.py
使用示例:
$ chmod 744 your_subprocess.py
$ cp your_subprocess.py /usr/local/bin/your_subprocess
$ your_subprocess
your_prompt$ ls
list_argv.py
your_file.py
your_ls.py
your_subprocess.py
your_prompt$ ls .
list_argv.py
your_file.py
your_ls.py
your_subprocess.py
your_prompt$ pwd
/Users/ox/_workspace/cmd_ln
your_prompt$ blah
/bin/sh: blah: command not found
your_prompt$ ^CTraceback (most recent call last):
File "/usr/local/bin/your_subprocess", line 8, in <module>
input = raw_input('your_prompt$ ')
KeyboardInterrupt
$
BREAK STUFF!
弄坏东西!
:-D
:-D
HAVE FUN!
玩得开心!
-ox
-牛