使用Python创建终端程序

时间:2021-08-18 17:29:08

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创建了一些基本的webapps并编写了一些简单的脚本。在使用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
  • 你会推荐什么样的模块,书籍或网站

5 个解决方案

#1


18  

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或grep的脉络;它是从命令行启动的,但它是非交互式的,可以在管道中使用,并与其他程序结合使用。典型的命令行程序没有交互式用户体验,而是依赖shell的历史记录和init文件进行自定义。

What you want to create is a curses application, that uses the full capabilities of the TTY as an interactive platform, for better or worse. To do that, look up curses.

你想要创建的是一个curses应用程序,它使用TTY的全部功能作为交互式平台,无论好坏。要做到这一点,请查看诅咒。

#2


22  

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:

如果你然后将你的文件复制到你的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:

#!/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:

#!/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.

用sys.argv替换raw_input()。

'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:

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

HAVE FUN!

-ox

#3


8  

You should take a look at the cmd module.

你应该看看cmd模块。

See the Python Cookbook for examples of its use.

有关其用法的示例,请参阅Python Cookbook。

#4


3  

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库。

#5


0  

If you want to create an standalone binary for a UNIX system, use freeze. If you want one for a Windows system, look into py2exe. To control locations of output on your screen, use the curses module.

如果要为UNIX系统创建独立二进制文件,请使用freeze。如果你想要一个Windows系统,请查看py2exe。要控制屏幕上输出的位置,请使用curses模块。

#1


18  

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或grep的脉络;它是从命令行启动的,但它是非交互式的,可以在管道中使用,并与其他程序结合使用。典型的命令行程序没有交互式用户体验,而是依赖shell的历史记录和init文件进行自定义。

What you want to create is a curses application, that uses the full capabilities of the TTY as an interactive platform, for better or worse. To do that, look up curses.

你想要创建的是一个curses应用程序,它使用TTY的全部功能作为交互式平台,无论好坏。要做到这一点,请查看诅咒。

#2


22  

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:

如果你然后将你的文件复制到你的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:

#!/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:

#!/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.

用sys.argv替换raw_input()。

'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:

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

HAVE FUN!

-ox

#3


8  

You should take a look at the cmd module.

你应该看看cmd模块。

See the Python Cookbook for examples of its use.

有关其用法的示例,请参阅Python Cookbook。

#4


3  

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库。

#5


0  

If you want to create an standalone binary for a UNIX system, use freeze. If you want one for a Windows system, look into py2exe. To control locations of output on your screen, use the curses module.

如果要为UNIX系统创建独立二进制文件,请使用freeze。如果你想要一个Windows系统,请查看py2exe。要控制屏幕上输出的位置,请使用curses模块。