簡體   English   中英

cmd模塊-python

[英]cmd module - python

我正在嘗試使用cmd模塊構建python shell。

from cmd import Cmd
import subprocess
import commands
import os 
from subprocess import call

class Pirate(Cmd): 
    intro = 'Welcome to shell\n'
    prompt = 'platform> '
    pass

if __name__ == '__main__':
    Pirate().cmdloop()

我正在嘗試使用python-cmd模塊構建外殼。 我正在嘗試構建這兩個功能。

歡迎來到殼牌

平台> ls

平台> cd ..

就像我要執行ls-在python shell或cd中列出該目錄中的所有文件。-返回上一個目錄

有人可以幫忙嗎? 我嘗試使用子進程庫..但沒有使其工作。

感謝您的幫助 ! 參考文檔: https : //docs.python.org/3/library/cmd.html

我很難弄清楚為什么您會需要這樣的東西,但這是我的嘗試:

import subprocess
from cmd import Cmd

class Pirate(Cmd): 
    intro = 'Welcome to shell\n'
    prompt = 'platform> '

    def default(self, line): # this method will catch all commands
        subprocess.call(line, shell=True)

if __name__ == '__main__':
    Pirate().cmdloop()

重點是使用default方法來捕獲作為輸入傳遞的所有命令。

def do_shell(self, line):
    "Run a shell command"
    print "running shell command:", line
    sub_cmd = subprocess.Popen(line,shell=True,stdout=subprocess.PIPE)
    output = sub_cmd.communicate()[0]
    print output
    self.last_output = output

在命令行中:

(Cmd)!ls
(Cmd)!pwd

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM