当前位置: 首页>>代码示例>>Python>>正文


Python platform.startswith函数代码示例

本文整理汇总了Python中sys.platform.startswith函数的典型用法代码示例。如果您正苦于以下问题:Python startswith函数的具体用法?Python startswith怎么用?Python startswith使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了startswith函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: check_platform

def check_platform():
  """Check the platform that script is running on.
  """
  if platform.startswith("win32") or platform.startswith("cygwin"):
    if version_info[0] < 3 and version_info[1] > 1:
      click.echo("Python version not supported, "
                 "Install python 3.x.x and try again")
开发者ID:andela,项目名称:offline-content-packager,代码行数:7,代码来源:check_platform.py

示例2: __init__

   def __init__(self, headless = False):
      if "UNO_PATH" in os.environ:
         office = os.environ["UNO_PATH"]
      else:
         if platform.startswith("win"):
            # XXX
            office = ""
         else:
            # Lets hope that works..
            office = '/usr/bin'
      office = os.path.join(office, "soffice")
      if platform.startswith("win"):
          office += ".exe"

      self._pidfile = "/tmp/markup_renderer_OOinstance" #XXX Windows compat needed
      xLocalContext = uno.getComponentContext()
      self._resolver = xLocalContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", xLocalContext)
      self._socket = "name=markupRendererPipe"

      args = ["--invisible", "--nologo", "--nodefault", "--norestore", "--nofirststartwizard"]
      if headless:
         args.append("--headless")

      if platform.startswith("win"):
         cmdArray = ['"' + office + '"']
      else:
         cmdArray = [office]
      cmdArray += args + ["--accept=pipe,%s;urp" % self._socket]
      if( not os.path.isfile(self._pidfile)):
         self.pid = os.spawnv(os.P_NOWAIT, office, cmdArray)
         f = open(self._pidfile,"w")
         f.write(str(self.pid))
开发者ID:joernchen,项目名称:openOfficeMarkup,代码行数:32,代码来源:myOfficehelper.py

示例3: Run

  def Run(self):
    if platform.startswith("win"):
      startupinfo = subprocess.STARTUPINFO()
      startupinfo.dwFlags |= STARTF_USESHOWWINDOW

    for cmd in self.script:
      evt = scriptEvent(msg = cmd, state = SCRIPT_RUNNING)
      wx.PostEvent(self.win, evt)
      args = shlex.split(str(cmd))
      try:
        if platform.startswith("win"):
          p = subprocess.Popen(args, stderr = subprocess.STDOUT,
                               stdout = subprocess.PIPE,
                               startupinfo = startupinfo)
        else:
          p = subprocess.Popen(args, stderr = subprocess.STDOUT,
                               stdout = subprocess.PIPE)
      except:
        evt = scriptEvent(msg = "Exception occurred trying to run\n\n%s" % cmd,
                          state = SCRIPT_CANCELLED)
        wx.PostEvent(self.win, evt)
        self.running = False
        return
      obuf = ''
      while not self.cancelled:
        o = p.stdout.read(1)
        if o == '': break
        if o == '\r' or o == '\n':
          if obuf.strip() != "":
            evt = scriptEvent(msg = obuf, state = SCRIPT_RUNNING)
            wx.PostEvent(self.win, evt)
          obuf = ''
        elif ord(o) < 32:
          pass
        else:
          obuf += o

      if self.cancelled:
        evt = scriptEvent(msg = None, state = SCRIPT_CANCELLED)
        wx.PostEvent(self.win, evt)
        p.kill()
        self.running = False
        p.wait()
        return

      rc = p.wait()
      if rc != 0:
        msg = "RC = " + str(rc) + " - Build terminated"
        evt = scriptEvent(msg = msg, state = SCRIPT_CANCELLED)
        wx.PostEvent(self.win, evt)
        self.running = False
        return

      evt = scriptEvent(msg = "", state = SCRIPT_RUNNING)
      wx.PostEvent(self.win, evt)

    evt = scriptEvent(msg = None, state = SCRIPT_FINISHED)
    wx.PostEvent(self.win, evt)

    self.running = False
开发者ID:applemuncy,项目名称:Teacup_Firmware,代码行数:60,代码来源:build.py

示例4: clearScreen

def clearScreen():
	import os
	if _platform.startswith("linux") or _platform.startswith("darwin"):
		# linux or mac
		os.system("clear")
	else:
		# windows
		os.system("cls")
开发者ID:C1PR14N055,项目名称:scraper,代码行数:8,代码来源:scra.py

示例5: get_os

def get_os():
    """
    Return system OS name.
    :return: string
    """
    if platform.startswith('linux'):
        return 'Linux'
    elif platform.startswith('win'):
        return 'Windows'
开发者ID:GrampusDev,项目名称:iAmVM,代码行数:9,代码来源:malware.py

示例6: retrieve_serial_number

def retrieve_serial_number():
    if platform.startswith("linux"):
        return ""
    elif platform.startswith("win"):
        output = check_output(["wmic", "bios", "get", "serialnumber"])
        output = output.strip().split("\n")[1]
        return output
    elif platform.startswith("darwin"):
        raise NotImplementedError
开发者ID:CoreSecurity,项目名称:pysap,代码行数:9,代码来源:dlmanager_decrypt.py

示例7: _init_socket

 def _init_socket(self):
     try:
         if ipaddress.IPv4Address(self.announce_addr).is_multicast:
             # TTL
             self._udp_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
             # TODO: This should only be used if we do not have inproc method! 
             self._udp_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1)
             # Usually, the system administrator specifies the 
             # default interface multicast datagrams should be 
             # sent from. The programmer can override this and
             # choose a concrete outgoing interface for a given
             # socket with this option. 
             #
             # this results in the loopback address?
             # host = socket.gethostbyname(socket.gethostname())
             # self._udp_sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(host))
             # You need to tell the kernel which multicast groups 
             # you are interested in. If no process is interested 
             # in a group, packets destined to it that arrive to 
             # the host are discarded.            
             # You can always fill this last member with the 
             # wildcard address (INADDR_ANY) and then the kernel 
             # will deal with the task of choosing the interface.
             #
             # Maximum memberships: /proc/sys/net/ipv4/igmp_max_memberships 
             # self._udp_sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, 
             #       socket.inet_aton("225.25.25.25") + socket.inet_aton(host))
             group = socket.inet_aton(self.announce_addr)
             mreq = struct.pack('4sL', group, socket.INADDR_ANY)
             self._udp_sock.setsockopt(socket.SOL_IP, 
                                       socket.IP_ADD_MEMBERSHIP, mreq)
             self._udp_sock.setsockopt(socket.SOL_SOCKET, 
                                       socket.SO_REUSEADDR, 1)
             #  On some platforms we have to ask to reuse the port
             try: 
                 socket.self._udp_sock.setsockopt(socket.SOL_SOCKET, 
                                       socket.SO_REUSEPORT, 1)
             except AttributeError:
                 pass
             self._udp_sock.bind((self.announce_addr, self._port))
         else:
             # Only for broadcast
             print("Setting up a broadcast beacon on %s:%s" %(self.announce_addr, self._port))
             self._udp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)       
             self._udp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
             #  On some platforms we have to ask to reuse the port
             try: 
                 self._udp_sock.setsockopt(socket.SOL_SOCKET, 
                                       socket.SO_REUSEPORT, 1)
             except AttributeError:
                 pass
             if platform.startswith("win") or  platform.startswith("darwin"):
                 self._udp_sock.bind(("0.0.0.0", self._port))
             else:
                 self._udp_sock.bind((self.announce_addr, self._port))
     except socket.error as msg:
         print(msg)
开发者ID:RoadRunnr,项目名称:pyre,代码行数:57,代码来源:zbeacon.py

示例8: openfile

def openfile(path):
    if platform.startswith('win') or platform == 'cygwin':
        subprocess.Popen(['explorer', '-p', '/select,', path])
    elif platform.startswith('linux'):
        subprocess.Popen(['xdg-open', path])
    elif platform.startswith('darwin'):
        subprocess.Popen(['open', path])
    else:
        raise NotImplementedError
开发者ID:avamsi,项目名称:Flash,代码行数:9,代码来源:utils.py

示例9: get_args

def get_args():
    import argparse
    from sys import platform

    # Parent parser
    mainparser = argparse.ArgumentParser(description='''Restores backups
            created by s3backup.py''')
    mainparser.add_argument('--version', action='version',
            version='s3restore %s; Suite version %s' %
            (version, config.version))
    subparsers = mainparser.add_subparsers(title='Commands',
            description='Type "command -h" for more info.')

    # Parser for the full-restore command
    fullparser = subparsers.add_parser('full-restore', help='''Restores all
            files from the backup.''')
    fullparser.add_argument('schedule', choices=['daily', 'weekly',
            'monthly'], help='Specifies the backup type to restore.')
    fullparser.add_argument('date', help='''The date the backup was made. A
            quoted string of the format "MM DD YYYY". A value of "last"
            restores the most recent backup.''')
    fullparser.add_argument('--force', action='store_true',
            help='''Restores all files, overwriting any with duplicate
            filenames.''')
    fullparser.add_argument('--force-no-overwrite', action='store_true',
            help='''Restores all file that no longer exist on the
            filesystem.''')
    fullparser.add_argument('-d', '--download-only', metavar='DIR',
            help='''Download and decrypt (if necessary) the archive to the
            given directory, but do not extract.''')
    if platform.startswith('win'):
        fullparser.add_argument('-f', '--filesystem', default='C',
                help='''The filesystem to use. Defaults to "C"''')
    fullparser.set_defaults(func=run_full_restore)

    # Parser for the browse-files command
    browseparser = subparsers.add_parser('browse-files', help='''Browse the
            archives and the archive's files and choose which to restore.
            ''')
    browseparser.add_argument('-s', '--schedule', choices=['daily',
            'weekly', 'monthly'], help='The type of backup to restore.')
    browseparser.add_argument('-d', '--date', help='''The date the backup
            was made. A string of the format "MM DD YYYY". A value of
            "last" browses the most recent backup.''')
    browseparser.add_argument('--archives', action='store_true',
            help='''Prints the list of archives. If given, all other
            arguments are ignored.''')
    if platform.startswith('win'):
        browseparser.add_argument('r', '--root', default='C',
                help='The root filesystem to restore to. Defaults to "C"')
    else:
        browseparser.add_argument('-r', '--root', default='/',
                help='''The root directory to restore to.''')
    browseparser.set_defaults(func=run_browse_files)

    return mainparser
开发者ID:rjframe,项目名称:s3-backup,代码行数:56,代码来源:s3restore.py

示例10: openfolder

def openfolder(path):
    if platform.startswith('win') or platform == 'cygwin':
        subprocess.Popen(['explorer', '/select,', path])
    elif platform.startswith('linux'):
        path = path.rsplit('/', 1)[0] + '/'
        subprocess.Popen(['xdg-open', path])
    elif platform.startswith('darwin'):
        path = path.rsplit('/', 1)[0] + '/'
        subprocess.Popen(['open', path])
    else:
        raise NotImplementedError
开发者ID:avamsi,项目名称:Flash,代码行数:11,代码来源:utils.py

示例11: display

def display(image_file_name):
  '''
  opens up the image in the default image viewer.
  '''
  from sys import platform
  from subprocess import call
  if platform.startswith('linux'):
    call(['xdg-open',image_file_name])
  elif platform.startswith('darwin'):
    call(['open',image_file_name])
  elif platform.startswith('win'):
    call(['start', image_file_name], shell=True)
开发者ID:code4tots,项目名称:scripts4golly,代码行数:12,代码来源:bmp.py

示例12: reconnect_xbee

    def reconnect_xbee(self):
    #search for available ports
        port_to_connect = ''
        while port_to_connect == '':

            #detect platform and format port names
            if _platform.startswith('win'):
                ports = ['COM%s' % (i + 1) for i in range(256)]
            elif _platform.startswith('linux'):
                # this excludes your current terminal "/dev/tty"
                ports = glob.glob('/dev/ttyUSB*')
            else:
                raise EnvironmentError('Unsupported platform: ' + _platform)

            ports_avail = []

            #loop through all possible ports and try to connect
            for port in ports:
                try:
                    s = serial.Serial(port)
                    s.close()
                    ports_avail.append(port)
                except (OSError, serial.SerialException):
                    pass

            if len(ports_avail) ==1:
                port_to_connect = ports_avail[0]

            elif len(ports_avail)==0:
                #No Serial port found, continue looping.
                print( "No serial port detected. Trying again...")
                time.sleep(1)

            elif len(ports_avail)>1:
                #Multiple serial ports detected. Get user input to decide which one to connect to
                #com_input = raw_input("Multiple serial ports available. Which serial port do you want? \n"+str(self.ports_avail)+":").upper();
                if self.default_serial == None:
                    raise EnvironmentError('Incorrect command line parameters. If there are multiple serial devices, indicate what port you want to be used using --serialport')
                elif self.default_serial.upper() in ports_avail:
                    port_to_connect = self.default_serial.upper()
                else:
                    raise EnvironmentError('Incorrect command line parameters. Serial port is not known as a valid port. Valid ports are:'+ str(ports_avail))

        #connect to xbee or uart
        ser = serial.Serial(port_to_connect, 115200)
        if self.uart_connection:
            self.xbee = UARTConnection(ser)
        else:
            self.xbee = ZigBee(ser)

        print('xbee connected to port ' + port_to_connect)
        return self
开发者ID:UWARG,项目名称:data-relay-station,代码行数:52,代码来源:receiver.py

示例13: OnPaint

    def OnPaint(self, event):

        if _plat.startswith('linux'):
            dc = wx.PaintDC(self)
            dc.Clear()
        elif _plat.startswith('darwin'):
            pass
        elif _plat.startswith('win'):
            if USE_BUFFERED_DC:
                dc = wx.BufferedPaintDC(self, self._Buffer)
            else:
                dc = wx.PaintDC(self)
                dc.DrawBitmap(self._Buffer, 0, 0)
                dc.Clear()
开发者ID:notklaatu,项目名称:stopgo,代码行数:14,代码来源:gui.py

示例14: _getOS

 def _getOS(self):
     '''
     Determins the operating system used to run code,
     and returns the terminal exit code to reset terminal features.
     :return: escape code for operating system that resets terminal print config.
     '''
     if platform.startswith("linux"): return self.reset_linux
     elif platform.startswith('darwin'): return self.reset_mac
     elif platform.startswith("win") or platform.startswith("cygwin"):
         return NotImplemented("Windows operating system does not support \
             color print nativly")
     elif platform.startswith("freebsd"): raise NotImplemented("Freebsd os \
             support is not implemented yet")
     else: raise NotImplemented("Could not find os type")
开发者ID:skaugvoll,项目名称:proggeTips,代码行数:14,代码来源:printColoredTextInTerminal.py

示例15: speak

def speak(what):
	if _platform.startswith("linux"):
		# linux
		import subprocess
		subprocess.call(['speech-dispatcher'])
		subprocess.call(['spd-say', what])
	elif _platform.startswith("darwin"):
		# MAC OS X
		os.system("say -v Fred " + what)
	elif _platform == "win32":
		# Windows
		import winsound
		freq = 2500 # Set Frequency To 2500 Hertz
		dur = 1000 # Set Duration To 1000 ms == 1 second
		winsound.Beep(freq, dur)
开发者ID:C1PR14N055,项目名称:scraper,代码行数:15,代码来源:scra.py


注:本文中的sys.platform.startswith函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。