def linkRepo(self, args): def ask(): res = raw_input( "Git repository already initialized and will be deleted.\nType repo name to confirm [{0}]:" .format(args[-1])) return res == args[-1] def initGitRepo(shell): if os.path.isdir(".git"): response = ask() if not response: print("Link canceled") sys.exit(1) shell.execute(["rm", "-rf", ".git"]) shell.execute(["git", "init"]) def setGitRemote(shell): shell.execute(["git", "remote", "add", "origin", gitRoute]) if len(args) not in [1, 2]: raise ModeError("Missing arguments", type="Repository") author = self._user if len(args) == 1 else args[0] gitRoute = "{0}@{1}:/{2}/{3}".format(self._user, self._gitServer, author, args[-1]) try: s = shell.Shell(cwd=os.getcwd()) initGitRepo(s) setGitRemote(s) except: pass
def main(): # Old version, pre-singleton... # # Initialize list of functions to poll # functs = [] # # # Initialize and link all objects # # # Joystick input # joy = Joy_control() # # Make it so that the printer function is called as part of the event function # joy.add_function_to_call(joy.print_joy_data) # functs.append(joy.poll_function) # # # Link joystick to arduino (arm) control # ser = Arduino_arm_control() # joy.add_function_to_call(ser.write_to_arm) # # functs = [] # # # Objects to demo multithreading. Don't actually do anything but print stuff # obj = shell.Demo_obj(2) # functs.append(obj.poll_function) # obj = shell.Demo_obj(1.2) # functs.append(obj.poll_function) # # # Initialize and start the program # # '8' is the maximum number of simultaneous threads, and 'functs' is the polling function list # s = shell.Shell(8, functs) # s.run() # Initialize list of functions to poll functs = [] # Objects to demo multithreading. They just print stuff to show it's working # obj = shell.Demo_obj(2) # functs.append(obj.poll_function) # obj = shell.Demo_obj(1.2) # functs.append(obj.poll_function) # initialize joystick input joy = Joy_control() # Link joystick to arduino (arm) control ser = Arduino_arm_control() joy.add_function_to_call(ser.print_power) # joy.add_function_to_call(joy.print_joy_data) functs.append(joy.poll_function) # Initialize and start the program # '8' is the maximum number of simultaneous threads, and 'functs' is the polling function list s = shell.Shell(8, functs) # Create the workAdder singleton wA = workAdder.workAdder(s) s.run() obj = shell.Demo_obj(3.14) wA.add_pq_obj(Pq_obj(3, stupid_print))
def main(): SetupLogging() config = LoadConfiguration() hostname = socket.gethostname() mqttClient = mqtt.Client() mqttClient.username_pw_set(config.Login, config.Password) myShell = shell.Shell(name=hostname, mqttClient=mqttClient, config=config) myShell.Run() return 0
def setup(): if not os.path.exists(ITUNES_LIBRARY): error('Could not find itunes library: %s' % ITUNES_LIBRARY) return False if not os.path.exists(ADB): error('Could not find adb - maybe the location of your Android SDK changed?') error('adb = %s' % adb) return False global SH ; SH = shell.Shell(aliases=SHELL_ALIASES) SH.cmd('restart') return check_num_devices() and check_device_state()
def cloneRepo(self, args, backup=False): if len(args) not in [1, 2]: raise ModeError("Missing arguments", type="Repository") author = self._user if len(args) == 1 else args[0] gitRoute = "{0}@{1}:/{2}/{3}".format(self._user, self._gitServer, author, args[-1]) try: s = shell.Shell(cwd=(self._tmp if backup else self._folder)) s.execute(["git", "clone", gitRoute]) except: pass
def run(self): sh = shell.Shell() #pt="/data0/temp/suda_rpt/auto_job/20180322165658440_531732.sql" #print pt #self.errfile = open(pt, 'w') #self.errfile.write('%s;' % (self.data['data']['hql'],)) #self.errfile.flush() cmd = 'presto --server 10.39.66.21:8080 --catalog hive --schema default --execute "' + self.data[ 'data']['hql'] + '"' print cmd code = sh.run(cmd, self.data['outfile'], self.data['errfile']) return code
def backupAllRepos(self, args): if len(args): raise ModeError("Too much arguments", type="Repository") response = self._api.list() for name in response["data"]["repositories"]: self.backupRepo([name], single=False) try: s = shell.Shell(cwd=self._tmp) s.execute(["tar", "cfz", "repositories.tar", "*"]) s.execute(["cp", "repositories.tar", os.getenv('PWD')]) except: pass shutil.rmtree(self._tmp)
def channel_opened(self, peer, channel_type, local_cid, queue): if not channel_type: # channel_type is None when the we initiated the channel. return if channel_type == "mpeer": asyncio.async(\ self._process_chord_packet(peer, local_cid, queue),\ loop=self.loop) return elif channel_type == "session": self.shells[local_cid] =\ shell.Shell(self.loop, peer, local_cid, queue) return
def backupRepo(self, args, single=True): if len(args) not in [1, 2]: raise ModeError("Missing arguments", type="Repository") if not os.path.exists(self._tmp): os.makedirs(self._tmp) self.cloneRepo(args, backup=True) path = self._tmp + "/" + args[-1] archive = args[-1] + ".tar" if not os.path.exists(path) or not single: return try: s = shell.Shell(cwd=self._tmp) s.execute(["tar", "cfz", archive, args[-1]]) s.execute(["cp", archive, os.getenv('PWD')]) except: pass shutil.rmtree(self._tmp)
def __init__(self): parser = argparse.ArgumentParser(description='A command minio tools. Version:1.0.') parser.add_argument("-m","--makebucket",help="create a new bucket.") parser.add_argument("-l","--listbuckets",help="list the all buckets",action="store_true") parser.add_argument("-e","--bucketexists",help="the bucket if exists") parser.add_argument("-r",'--removebucket',help="remove the buckets") parser.add_argument("--listobjects",help="list the all objects") parser.add_argument("--getbucketpolicy",help="get bucket policy") parser.add_argument("--setbucketpolicy", help="set bucket policy",action='store') parser.add_argument("--bucket",'-b',help="set bucket name") parser.add_argument("--getbucketnotification", help="get bucket notification") parser.add_argument("shell",help="connect the remote server as shell") args = parser.parse_args() cminio_operation = operation.Operation() if args.makebucket: cminio_operation.make_bucket(args.makebucket) elif args.listbuckets: cminio_operation.list_buckets() elif args.bucketexists: cminio_operation.bucket_exists(args.bucketexists) elif args.listobjects: prefix = raw_input('the prefix of objects that should be listed(None):') recursive = raw_input("(Y) indicates recursive style listing and (N) indicates directory listing delimited by '/'(Y/N):") while recursive != 'Y' and recursive != 'N': recursive = raw_input( "(Y) indicates recursive style listing and (N) indicates directory listing delimited by '/'(Y/N):") prefix_x = None if (prefix == '') else prefix recursive_e = True if (recursive == 'Y') else False cminio_operation.list_objects(prefix=prefix_x, bucket_name=args.listobjects,recursive=recursive_e) elif args.getbucketpolicy: cminio_operation.get_bucket_policy(args.getbucketpolicy) elif args.setbucketpolicy: if args.bucket: cminio_operation.set_bucket_policy(args.bucket,args.setbucketpolicy) else: raise Exception("No such argument: --bucket") elif args.getbucketnotification: cminio_operation.get_bucket_notification(args.getbucketnotification) #shell elif args.shell: shell_cmd = shell.Shell()
def main(): try: get_uname = raw_input("{}Enter the Shell user Name :".format( colors.red)) store_shellname = shell.Shell(get_uname) show_shellname = store_shellname.GetName() get_input_from_user = raw_input(show_shellname) shell_checker = checkshell.CheckShell(get_input_from_user) pass except IOError as identifier: print("{}shell faild{}".format(colors.red, colors.reset)) pass else: pass finally: pass time.sleep(30)
def main(): # Initialize list of functions to poll functs = [] # Initialize and link all objects # initialize joystick input joy = Joy_control() # Link joystick to console output joy.add_function_to_call(joy.print_joy_data) functs.append(joy.poll_function) # Link joystick to arduino (arm) control ser = Arduino_arm_control() joy.add_function_to_call(ser.write_to_arm) # Initialize and start the program # '8' is the maximum number of simultaneous threads, and 'functs' is the polling function list s = shell.Shell(8, functs) s.run()
def createMpdController(current_dir, config, extra_pages): mpdhost = config.get("mpd-host", "localhost") mpdport = config.get("mpd-port", 6600) httpport = config.get("http-port", 3344) cardsfile = config.get("cards-file", "cards.txt") jamendo_clientid = config.get("jamendo-clientid", "") jamendo_username = config.get("jamendo-username", "") use_card_service = config.get("use-card-service", False) log = config.get("log", False) notifierx = notifier.Notifier() mpdplayerx = mpdplayer.MpdPlayer(mpdhost, mpdport, notifierx.notify) mpdsourcex = mpdsource.MpdSource(mpdplayerx.client) radiosx = radiosource.RadioSource(mpdplayerx) shellx = shell.Shell() pages = extra_pages + [ ("Mpd", lambda c: mpdsource.SearchPage(c, mpdsourcex)), ("Playlists", lambda c: mpdsource.PlaylistPage(c, mpdsourcex)), ("Radio", lambda c: radiosource.RadioPage(c, radiosx)), ] handlers = mpdsourcex.handlers() + [radiosx.play_radio] enrichers = [mpdsourcex.enrich_track] if jamendo_clientid: jamapi = jamendo.JamendoApi(jamendo_clientid) handler = jamendo.JamendoActionHandler(self.mpdplayer, jamapi) pages += [ ("Jamendo Search", lambda c: jamendo.SearchPage(c, jamapi)), ("Jamendo Radio", lambda c: jamendo.RadioPage(c, jamapi)), ("Jamendo Likes", lambda c: jamendo.LikesPage(c, jamapi, jamendo_username)), ] handlers += handler.handlers() enrichers += handler.enrichers() actions = mpdplayerx.actions() + shellx.actions() services = [mpdplayerx] instance = Server(current_dir, cardsfile, log, httpport, notifierx, use_card_service, handlers, enrichers, actions, pages, services) return instance
import shell as sh rekonq_help_message = """Usage: rekonq.py [OPTIONS...] Or: rekonq.py -h Options: -i <file> Recover saved game from file -h Show this help menu """ try: opts, args = getopt.getopt(sys.argv[1:], 'hi:') except getopt.GetoptError: print(rekonq_help_message) sys.exit(1) for opt, arg in opts: if opt == '-h': print(rekonq_help_message) sys.exit(0) elif opt in ['-i', '--input-file=']: # Load game from file shell = sh.Shell(True) shell.load_game(arg) shell.start_shell() sys.exit(0) shell = sh.Shell(False) shell.start_shell()
import threading import string import shell import copy import sys STDOUT = shell.STDOUT STDERR = shell.STDERR STDIN = shell.STDIN SHELL = shell.Shell() DEFAULT_SIZE = shell.DEFAULT_SIZE BLANK = (" " * DEFAULT_SIZE[0] + "\n") * DEFAULT_SIZE[1] class WritingCursor: def __init__(self): self.position = shell.WRITING_CURSOR.position def __setitem__(self, key, value): self.set(*key, value) def clear(self): shell.WRITING_CURSOR.clear() def reset(self): shell.WRITING_CURSOR.reset() def move_by(self, delta_x, delta_y): shell.WRITING_CURSOR.move_by(delta_x, delta_y)
max_gaming_count = int(config['gaming_sessions_number']) #logging module configuration logging.config.fileConfig(config['log_conf_path'], disable_existing_loggers=False) log = logging.getLogger(__name__) log.info("starting up server software - vers: %s", __vers__) log.debug("config:") log.debug("max_gaming_count: %s", max_gaming_count) log.debug("table_list: \n%s", table_list) log.debug("db_name: %s", config['users_db_path']) #creating Shell object #It is on the begining, because it will capture all the data from the beginning sh = shell.Shell(config['server_ip'], config['port'], user_status) #connection to database log.info("connecting to database: %s", config['users_db_path']) try: user_db = sqlite3.connect(config['users_db_path']) log.debug("databse object: OK") cur = user_db.cursor() log.debug("cursor object: OK") except sqlite3.Error as e: log.exception("sqlite3 error: %s", e.args[0]) else: log.info("database connection: OK") #checking if there are all tables #create if some doesnt excist
def lvsStat(): ret = [] ts = int(time.time()) try: sh = shell.Shell() sh.run(my_script) if sh.code == 0: lvs_total_stat = sh.output() for s in lvs_total_stat: s = s.strip().split() metric = { "endpoint": ENDPOINT, "metric": "lvs.%s" % s[0].lower(), "tags": "", "timestamp": ts, "value": s[1], "step": 60, "counterType": "GAUGE" } ret.append(metric) fp = open('/tmp/lvs.stats', 'r') for line in fp: line = line.strip().split() protocal = line[0] vip = line[1] vip_cps = line[2] vip_cps_metrics = { "endpoint": ENDPOINT, "metric": "lvs.vip.conns", "tags": "protocal=%s, vip=%s" % (protocal, vip), "timestamp": ts, "value": vip_cps, "step": 60, "counterType": "GAUGE" } ret.append(vip_cps_metrics) vip_in_pps = line[3] vip_in_pps_metrics = { "endpoint": ENDPOINT, "metric": "lvs.vip.inpkts", "tags": "protocal=%s, vip=%s" % (protocal, vip), "timestamp": ts, "value": vip_in_pps, "step": 60, "counterType": "GAUGE" } ret.append(vip_in_pps_metrics) vip_out_pps = line[4] vip_out_pps_metrics = { "endpoint": ENDPOINT, "metric": "lvs.vip.outpkts", "tags": "protocal=%s, vip=%s" % (protocal, vip), "timestamp": ts, "value": vip_out_pps, "step": 60, "counterType": "GAUGE" } ret.append(vip_out_pps_metrics) vip_in_bps = line[5] vip_in_bps_metrics = { "endpoint": ENDPOINT, "metric": "lvs.vip.inbytes", "tags": "protocal=%s, vip=%s" % (protocal, vip), "timestamp": ts, "value": vip_in_bps, "step": 60, "counterType": "GAUGE" } ret.append(vip_in_bps_metrics) vip_out_bps = line[6] vip_out_bps_metrics = { "endpoint": ENDPOINT, "metric": "lvs.vip.outbytes", "tags": "protocal=%s, vip=%s" % (protocal, vip), "timestamp": ts, "value": vip_out_bps, "step": 60, "counterType": "GAUGE" } ret.append(vip_out_bps_metrics) except: metric = { "endpoint": ENDPOINT, "metric": "lvs.noinstall", "tags": "", "timestamp": ts, "value": 0, "step": 60, "counterType": "GAUGE" } ret.append(metric) return ret
def get_shell(self, user, agent=None): """ Get a shell for a specific agent/user. """ return shell.Shell(self, user, agent=agent, game=self.game)
def fire(self): self.app.snd_shell_fired.play() self.app.shell_list.append(shell.Shell(self.app, self.to_target_orientation(self.app.ship)))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # pylint: disable=E0401 # pylint: disable=E0401 """ Welcome In Pig Dice!. The game is easy. Try to roll the dice and not gitting values 1 and 6, or you lose your score and turn. The winner who reach 50 points first. To start the game, Enter 'start 1' to play against the computer 'start 2' to play with two players. If you choose to play against the computer, you are able to change the level when ever you want. I expect to change your name by entering 'name (Your Name)' Prese help or ? to get more about commands """ import shell if __name__ == '__main__': print(__doc__) shell.Shell().cmdloop()
def __init__(self, argv=[], shelltype='python', banner=[], filename=None, size=100): """ Console interface building + initialization""" # GTK interface self.do_quit = False gtk.ScrolledWindow.__init__(self) self.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC) self.set_shadow_type (gtk.SHADOW_NONE) self.set_border_width(0) self.view = gtk.TextView() self.view.modify_font (pango.FontDescription("Mono 10")) self.view.set_editable (True) self.view.set_wrap_mode(True) self.view.set_left_margin(0) self.view.set_right_margin(0) self.buffer = self.view.get_buffer() self.buffer.create_tag ('title', indent = 2, weight=pango.WEIGHT_BOLD, foreground='blue', font='Mono 12') self.buffer.create_tag ('subtitle', indent = 2, foreground='blue', font='Mono 8') self.buffer.create_tag ('output', foreground = 'blue', font='Mono 10') self.buffer.create_tag ('error', foreground='red', style=pango.STYLE_OBLIQUE, font='Mono 10') self.buffer.create_tag ('prompt', foreground='blue', weight=pango.WEIGHT_BOLD, font='Mono 10') self.buffer.create_tag('0') self.color_pat = re.compile('\x01?\x1b\[(.*?)m\x02?') for code in ansi_colors: self.buffer.create_tag(code, foreground=ansi_colors[code], weight=700) for text, style in banner: self.write (text, style) iter = self.buffer.get_iter_at_mark(self.buffer.get_insert()) self.buffer.create_mark ('linestart', iter, True) self.view.add_events(gtk.gdk.KEY_PRESS_MASK) self.view.connect ('key-press-event', self.key_press_event) self.add(self.view) self.show_all() self.killbuffer = None # Console stuff self.argv = argv self.history_init(filename, size) self.cout = StringIO() self.cout.truncate(0) if shelltype=='ipython': self.shell = ishell.Shell(argv,locals(),globals(), cout=self.cout, cerr=self.cout, input_func=self.raw_input) else: self.shell = shell.Shell(locals(),globals()) self.interrupt = False self.input_mode = False self.input = None self.stdout = ConsoleOut (self, sys.stdout.fileno(), 'output') self.stderr = ConsoleOut (self, sys.stderr.fileno(), 'error') self.stdin = ConsoleIn (self, sys.stdin.fileno()) # Create a named pipe for system stdout/stderr redirection self.fifoname = tempfile.mktemp() if not os.path.exists (self.fifoname): os.mkfifo (self.fifoname) self.piperead = os.open (self.fifoname, os.O_RDONLY | os.O_NONBLOCK) self.pipewrite = os.open (self.fifoname, os.O_WRONLY | os.O_NONBLOCK) self.shell.eval(self) self.cout.truncate(0)
def main(): """Funcion principal""" s.Shell().cmdloop()
#!/usr/bin/env python import os, sys, inspect importDir = os.path.abspath( os.path.join(os.path.dirname(__file__), '..', '..', 'lib', 'python2.7')) print importDir sys.path.append(importDir) import shell sh = shell.Shell("foo") sh.help()
#!/usr/bin/env python """ Copyright (C) 2015, Radmon. Use of this source code is governed by the MIT license that can be found in the LICENSE file. """ import shell from papery import create_app sh = shell.Shell(__name__) @sh.task def install(args): sh.call('pip', 'install', '-r', 'requirements.txt') sh.cd('theme') sh.call('npm', 'install', '--production') sh.cd('..') @sh.task def install_dev(args): sh.call('pip', 'install', '-r', 'requirements-dev.txt') sh.cd('theme') sh.call('npm', 'install', '--dev') sh.cd('..') @sh.task def rebuild_theme(args):
import shell import engine engine = engine.Engine() shell = shell.Shell(engine) shell.start()
import git import migration import pip import sass import server import shell import test import curl migrates = migration.Migrate() tests = test.Test() local_shell = shell.Shell() pf = pip.PipFreeze() pi = pip.PipInstall() local_server = server.Server() local_sass = sass.SassCompile()
def main(): """ Main entry point for the python portion of the app. sys.argv[1] is the name of the shell type (bash, tcsh, etc.) that is being used. sys.argv[2] is the name of the command that is to be run. :return: Nothing. """ # Make sure this script is owned by root and only writable by root. permissions.validate_app_permissions() # Create a shell object to handle shell specific tasks shell_obj = shell.Shell(sys.argv[1]) # Only handle specific types of requests if sys.argv[2] not in LEGAL_COMMANDS: display.display_error("Unknown command: " + sys.argv[2]) display.display_usage() sys.exit(1) # Read the env and stuff its settings into the constants settings = read_user_settings_from_env() # =========================== if sys.argv[2] == "setup": setup.setup(shell_obj, settings) sys.exit(0) # =========================== if sys.argv[2] == "refresh": setup.setup(shell_obj, settings) sys.exit(0) # =========================== if sys.argv[2] == "complete_use": completions.complete_use(sys.argv[3]) # =========================== if sys.argv[2] == "complete_unuse": completions.complete_unuse(sys.argv[3]) # =========================== if sys.argv[2] == "use": if len(sys.argv) != 4: display.display_error("use: Wrong number of arguments.") sys.exit(1) stdin = list( sys.stdin ) # List of existing aliases in the shell. Used to store for history and unuse purposes. use.use(shell_obj, sys.argv[3], stdin, settings) # =========================== if sys.argv[2] == "used": used.used(shell_obj) # =========================== if sys.argv[2] == "unuse": stdin = list( sys.stdin ) # List of existing aliases in the shell. Used to store for history and unuse purposes. if len(sys.argv) > 3: branch_name = use.get_branch_from_use_pkg_name(sys.argv[3]) unuse.unuse(shell_obj, branch_name, stdin) # =========================== if sys.argv[2] == "get_branch_from_use_pkg_name": branch_name = use.get_branch_from_use_pkg_name(sys.argv[3]) print(branch_name)