sys.platform.lower

Here are the examples of the python api sys.platform.lower taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

31 Examples 7

Example 1

Project: robotframework
Source File: PlatformLib.py
View license
def get_os_platform():
    """return platform name, but for Jython it uses os.name Java property"""
    ver = sys.platform.lower()
    if ver.startswith('java'):
        import java.lang
        ver = java.lang.System.getProperty("os.name").lower()
    print('platform: %s' % (ver))
    return ver

Example 2

Project: montepython_public
Source File: try_ifort.py
View license
def configure_(ctx):
  if ctx.options.fortran_flagline:
    conf.parse_flags(ctx.options.fortran_flagline,uselib="fc_runtime")
  if sys.platform.lower()=="darwin":
    ctx.env.fcshlib_PATTERN = 'lib%s.dylib'
  
  
  ctx.env.has_ifort = False
  if not Options.options.gfortran:
    try:
      ifort_conf(ctx)
      return
    except Exception,e:
      if Options.options.ifort:
        raise
      Logs.pprint("PINK", "ifort not found, defaulting to gfortran (cause: '%s')"%e)
  gfortran_conf(ctx)

Example 3

Project: tahoe-lafs
Source File: common.py
View license
def platform_uses_lettercolon_drivename():
    if ("win32" in sys.platform.lower()
        or "cygwin" in sys.platform.lower()
        or pretend_platform_uses_lettercolon):
        return True
    return False

Example 4

Project: tahoe-lafs
Source File: test_node.py
View license
    def test_secrets_dir_protected(self):
        if "win32" in sys.platform.lower() or "cygwin" in sys.platform.lower():
            # We don't know how to test that unprivileged users can't read this
            # thing.  (Also we don't know exactly how to set the permissions so
            # that unprivileged users can't read this thing.)
            raise unittest.SkipTest("We don't know how to set permissions on Windows.")
        basedir = "test_node/test_secrets_dir_protected"
        fileutil.make_dirs(basedir)
        n = TestNode(basedir)
        self.failUnless(isinstance(n, TestNode))
        privdir = os.path.join(basedir, "private")
        st = os.stat(privdir)
        bits = stat.S_IMODE(st[stat.ST_MODE])
        self.failUnless(bits & 0001 == 0, bits)

Example 5

Project: tahoe-lafs
Source File: fileutil.py
View license
def move_into_place(source, dest):
    """Atomically replace a file, or as near to it as the platform allows.
    The dest file may or may not exist."""
    if "win32" in sys.platform.lower():
        remove_if_possible(dest)
    os.rename(source, dest)

Example 6

Project: vivisect
Source File: unittest.py
View license
def main():

    print('running bare minimum vtrace tests')
    runTests(tests)
    print('')
    print('running architecture specific tests')
    if struct.calcsize('P') == 4:
        runTests(tests32)
    elif struct.calcsize('P') == 8:
        runTests(tests64)
    else:
        raise Exception('unsupported bitness')
    print('')

    print('running platform specific tests')
    if 'win' in sys.platform.lower():
        runTests(windows)

Example 7

Project: foolscap
Source File: util.py
View license
def move_into_place(source, dest):
    """Atomically replace a file, or as near to it as the platform allows.
    The dest file may or may not exist."""
    # from Tahoe
    if "win32" in sys.platform.lower():
        try:
            os.remove(dest)
        except:
            pass
    os.rename(source, dest)

Example 8

Project: EulerPy
Source File: setup.py
View license
def requirements():
    with open('requirements.txt') as f:
        install_requires = [line.strip() for line in f]

    # Terminal colors for Windows
    if 'win32' in sys.platform.lower():
        install_requires.append('colorama')

    return install_requires

Example 9

Project: rjsmin
Source File: setup.py
View license
def setup(args=None, _manifest=0):
    """ Main setup function """
    from _setup.ext import Extension

    if 'java' in _sys.platform.lower():
        # no c extension for jython
        ext = None
    else:
        ext=[Extension('_rjsmin', sources=['rjsmin.c'])]

    return run(script_args=args, ext=ext, manifest_only=_manifest)

Example 10

Project: rjsmin
Source File: setup.py
View license
def setup(args=None, _manifest=0):
    """ Main setup function """
    from _setup.ext import Extension

    if 'java' in _sys.platform.lower():
        # no c extension for jython
        ext = None
    else:
        ext=[Extension('_rjsmin', sources=['rjsmin.c'])]

    return run(script_args=args, ext=ext, manifest_only=_manifest)

Example 11

Project: montepython_public
Source File: any_lapack.py
View license
def configure(ctx):
  #always assume that I need a dedicated include file.
  
  if ctx.options.lapack_apple:
    ctx.start_msg("Check apple lapack")
    if sys.platform.lower()!="darwin":
      ctx.end_msg("not on darwin ! Got '%s'"%sys.platform,color="YELLOW")
      raise Errors.WafError("cannot find apple lapack")
    ctx.end_msg("ok")
    lapack_extradefs = ["HAS_LAPACK"]
    lapack_libs = ["BLAS","LAPACK"]
    lapack_includes = ["lapack_clik.h"]
    lapack_extradefs += ["LAPACK_CLIK"]
    ctx.options.lapack_include = osp.join(ctx.env.PREFIX,"include")
    ctx.options.lapack_lib = "/System/Library/Frameworks/Accelerate.framework/Versions/Current/Frameworks/vecLib.framework/Versions/Current"
    do_include(ctx,"%s_")

  elif ctx.options.lapack_mkl:
    # parse version
    ctx.start_msg("Check mkl version")
    if ctx.options.lapack_mkl_version.strip()[:4] not in ("10.0","10.1","10.2","10.3"):
      ctx.end_msg(ctx.options.lapack_mkl_version.strip(),color="YELLOW")
      raise Errors.WafError("Cannot understand mkl version '%s'"%ctx.options.lapack_mkl_version.strip())
    version = int(ctx.options.lapack_mkl_version.strip()[:4].split(".")[1])
    ctx.end_msg("10.%d"%version)
    lapack_extradefs = ["HAS_LAPACK"]
    lapack_extradefs += ["HAS_MKL"]
    lapack_includes = ["mkl_lapack.h","mkl_blas.h"]
    lapack_libs = []
    tag = sys.platform.lower()
    if tag=="darwin":
      pass
    elif "linux" in tag:
      tag="linux"
    else:
      raise Errors.WafError("unknown platform '%s'"%tag)
    tag+="_10.%d"%version
    mopt = ctx.env.mopt
    if "64" in mopt:
      tag+="_64"
    else:
      tag +="_32"

    if sys.platform.lower()!='darwin':
      #I need to create my own lapack ! 
      cmdline = """gcc -shared -Bdynamic  %(func_list)s  -Wl,--start-group %(ars)s  -Wl,--end-group %(Lomp)s %(omp)s -o "%(res)s" """
      cmdlist = {}
      cmdlist["func_list"] = " ".join(["-u %s_"%v for v in lapack_funcs.split()])
      cmdlist["ars"] = " ".join([osp.join(mkl_options[tag][0]%(ctx.options.lapack_mkl),"lib%s.a"%v.strip()) for v in mkl_options[tag][1].split("-l") if v.strip() and v.strip()[:3]=="mkl"])
      cmdlist["Lomp"] = " ".join("-L%s"%v.strip() for v in ctx.env.LIBPATH_fc_runtime if v.strip())
      cmdlist["omp"] = " ".join([v.strip() for v in mkl_options[tag][1].split() if v.strip() and "mkl" not in v])
      cmdlist["res"] = osp.join(ctx.env.LIBDIR,ctx.env.cshlib_PATTERN%"clik_mkl")
      cmdline = cmdline%cmdlist
      #print cmdline
      ctx.start_msg("create specific mkl lib")
      llgo,llge = ctx.cmd_and_log(cmdline, output=waflib.Context.BOTH)
      #print llgo
      #print llge
      ctx.end_msg(cmdlist["res"])
      ctx.options.lapack_link = "-lclik_mkl "+cmdlist["omp"]
      ctx.options.lapack_lib = ctx.env.LIBDIR+":".join([""]+ctx.env.LIBPATH_fc_runtime)
      ctx.options.lapack_include =  ctx.options.lapack_mkl+"/include"

    else:
      ctx.options.lapack_link = mkl_options[tag][1]
      ctx.options.lapack_lib = mkl_options[tag][0]%(ctx.options.lapack_mkl)+":".join([""]+ctx.env.LIBPATH_fc_runtime)
      if "framework" in ctx.options.lapack_mkl.lower():
        ctx.options.lapack_include =  ctx.options.lapack_mkl+"/Headers"
      else:
        ctx.options.lapack_include =  ctx.options.lapack_mkl+"/include"

    #try:
    #  atl.conf_lib(ctx,"lapack",lapack_libs,lapack_funcs.split(),lapack_includes,defines=lapack_extradefs,install=installlapack)
    #except Exception,e:
    #  pass

  #lapack_extradefs = ["HAS_LAPACK"]
  #lapack_libs = ["BLAS","LAPACK"]
  #lapack_includes = ["lapack.h","blas.h"]

  #if "mkl" in ctx.options.lapack_lib.lower() or "mkl" in ctx.options.lapack_include.lower() or "mkl" in ctx.options.lapack_link or ctx.options.lapack_mkl:
  #  ctx.env.mkl = True
  #  lapack_extradefs += ["HAS_MKL"]
  #  lapack_includes = ["mkl_lapack.h","mkl_blas.h"]
  #  if ctx.options.lapack_mkl:
  #    if ctx.env.has_ifort==False:
  #      raise Exception("cannot use MKL without ifort")
  #    if "framework" in ctx.options.lapack_mkl.lower():
  #      # guess we are on macosx
  #      # get the path of the framework
  #      if ctx.options.lapack_mkl[-1] == "/":
  #        fpath,fname = osp.split(ctx.options.lapack_mkl[:-1])
  #      else:
  #        fpath,fname = osp.split(ctx.options.lapack_mkl)
  #      fname = fname.split(".")[0]
  #      ctx.options.lapack_include =  ctx.options.lapack_mkl+"/Headers"
  #      ctx.options.lapack_lib =  ctx.options.lapack_mkl+"/Libraries/universal"
  #      if ctx.options.lapack_link=="":
  #        ctx.options.lapack_link = "-lmkl_intel_lp64 -lmkl_intel_thread -lmkl_core"
  #    else:
  #      # assume it's 10 on linux
  #      # check whether it's 10.3
  #      if ctx.options.m32:
  #        libsuffix="/lib/32"
  #        libdep = "-lmkl_intel"
  #      else:
  #        libsuffix="/lib/em64t"
  #        libdep = "-lmkl_intel_lp64"
  #      if ctx.options.lapack_link=="":
  #        ctx.options.lapack_link = "-lmkl_lapack -lmkl_intel_thread -lmkl_core -liomp5 -lm -lpthread -lmkl_def" + libdep
  #      if not ctx.options.m32 and osp.exists(ctx.options.lapack_mkl+"/lib/intel64"):
  #        libsuffix="/lib/intel64"
  #        ctx.options.lapack_link = "-lmkl_intel_thread -lmkl_core -liomp5 -lm -lpthread -lmkl_def" + libdep
  #      ctx.options.lapack_include=ctx.options.lapack_mkl+"/include"
  #      ctx.options.lapack_lib=ctx.options.lapack_mkl+libsuffix+":".join([""]+ctx.env.LIBPATH_fc_runtime)
  elif atl.upgrade(ctx,"lapack") or ctx.options.lapack_islocal or ctx.options.lapack_forceinstall or atl.shouldIinstall_all(ctx,"lapack"):
    ctx.env.append_value("LIBPATH_lapack",ctx.env.LIBPATH_fc_runtime)
    ctx.env.append_value("RPATH_lapack",ctx.env.RPATH_fc_runtime)
    ctx.env.append_value("LIB_lapack",ctx.env.LIB_fc_runtime)
    lapack_libs = ["lapack_clik","blas_clik"]
    lapack_includes = ["lapack_clik.h"]
    lapack_extradefs = ["HAS_LAPACK"]
    lapack_extradefs += ["LAPACK_CLIK"]
  else:
    lapack_libs = []
    lapack_includes = ["lapack_clik.h"]
    lapack_extradefs = ["HAS_LAPACK"]
    lapack_extradefs += ["LAPACK_CLIK"]
    do_include(ctx)

  atl.conf_lib(ctx,"lapack",lapack_libs,lapack_funcs.split(),lapack_includes,defines=lapack_extradefs,install=installlapack)

Example 12

Project: psutil
Source File: test_system.py
View license
    def test_os_constants(self):
        names = ["POSIX", "WINDOWS", "LINUX", "OSX", "FREEBSD", "OPENBSD",
                 "NETBSD", "BSD", "SUNOS"]
        for name in names:
            self.assertIsInstance(getattr(psutil, name), bool, msg=name)

        if os.name == 'posix':
            assert psutil.POSIX
            assert not psutil.WINDOWS
            names.remove("POSIX")
            if "linux" in sys.platform.lower():
                assert psutil.LINUX
                names.remove("LINUX")
            elif "bsd" in sys.platform.lower():
                assert psutil.BSD
                self.assertEqual([psutil.FREEBSD, psutil.OPENBSD,
                                  psutil.NETBSD].count(True), 1)
                names.remove("BSD")
                names.remove("FREEBSD")
                names.remove("OPENBSD")
                names.remove("NETBSD")
            elif "sunos" in sys.platform.lower() or \
                    "solaris" in sys.platform.lower():
                assert psutil.SUNOS
                names.remove("SUNOS")
            elif "darwin" in sys.platform.lower():
                assert psutil.OSX
                names.remove("OSX")
        else:
            assert psutil.WINDOWS
            assert not psutil.POSIX
            names.remove("WINDOWS")

        # assert all other constants are set to False
        for name in names:
            self.assertIs(getattr(psutil, name), False, msg=name)

Example 13

Project: pypot
Source File: __init__.py
View license
def _get_available_ports():
    """ Tries to find the available serial ports on your system. """
    if platform.system() == 'Darwin':
        return glob.glob('/dev/tty.usb*')

    elif platform.system() == 'Linux':
        return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyAMA*')

    elif sys.platform.lower() == 'cygwin':
        return glob.glob('/dev/com*')

    elif platform.system() == 'Windows':
        import _winreg
        import itertools

        ports = []
        path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
        key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path)

        for i in itertools.count():
            try:
                ports.append(str(_winreg.EnumValue(key, i)[1]))
            except WindowsError:
                return ports
    else:
        raise EnvironmentError('{} is an unsupported platform, cannot find serial ports !'.format(platform.system()))
    return []

Example 14

Project: shellsploit-framework
Source File: exe.py
View license
def detectOS():
    from sys import platform 

    if architectureDetect() == 32:
        if platform.lower() == "linux" or platform == "linux2":
            return "linux86"
        #elif platform.lower() == "darwin":
            #print "mac osx"
        elif platform.lower() == "win32":
            return "windows"
        elif platform.lower() == "sunos":
            return "solarisx86"
        elif "freebsd" in platform.lower():
            return "freebsdx86"
        elif "openbsd" in platform.lower():
            return "openbsdx86"

    #I will fix it soon :(
    elif architectureDetect() == 64:
        if "freebsd" in platform.lower():
            return "freebsdx64"
        elif "win32" in platform.lower():
            return "windows"

    else:
        #This is can be possible ? ..
        print ("Not supported architecture ..")

Example 15

Project: montepython_public
Source File: mbits.py
View license
def configure(ctx):
  import sys
  from waflib import Utils,Errors
  if ctx.options.m32 and ctx.options.m64:
    raise Errors.WafError("You must choose either m32 of m64 !")
  #32 bits
  if ctx.options.m32==False and ctx.options.m64==False:
    ctx.options.m64=True
  if sys.platform.lower()=="darwin":
    mopt = ""
    if ctx.options.m64:
      mopt += "-arch x86_64 "
    if ctx.options.m32:    
      mopt += "-arch i386 "    
  else:
    mopt = "-m64"
    if ctx.options.m32:
      mopt = "-m32"
      
  ctx.env.mopt=mopt
  ctx.env.append_value('CCFLAGS',mopt)
  ctx.env.append_value('LINKFLAGS',mopt)
  ctx.start_msg("Setting architecture flag to") 
  ctx.end_msg(mopt)

Example 16

Project: montepython_public
Source File: osx_shlib.py
View license
def configure(ctx):
  import sys
  ctx.env.shsuffix = "so"
  if sys.platform.lower()=="darwin":
    ctx.env.shsuffix = "dylib"

Example 17

Project: montepython_public
Source File: try_ifort.py
View license
def ifort_conf(ctx):
  import waflib
  import os
  ctx.env.FC=[]
  ctx.load('ifort')
  if sys.platform.lower()=="darwin":
    ctx.env.LINKFLAGS_fcshlib = ['-dynamiclib']
  ctx.env.append_value('FCFLAGS',ctx.env.mopt.split())
  ctx.env["FCFLAGS_fc_omp"]=[]
  ctx.env.append_value("FCFLAGS_fc_omp","-openmp")
  ctx.env.FCSHLIB_MARKER = [""]
  ctx.env.FCSTLIB_MARKER = [""]
  ctx.check_cc(
    errmsg="failed",msg='Compile a test code with ifort',
    mandatory=1,fragment = "program test\n  WRITE(*,*) 'hello world'\n end program test\n",compile_filename='test.f90',features='fc fcprogram')
  if not ctx.options.fortran_flagline:
    ctx.start_msg("retrieve ifort link line")
    try:
      #print "%s %s -dryrun -dynamiclib -shared-intel -no-cxxlib dummy.f90"%(ctx.env.FC," ".join(ctx.env.FCFLAGS))
      llgo,llge = ctx.cmd_and_log("%s %s -dryrun -dynamiclib -shared-intel -no-cxxlib dummy.f90"%(ctx.env.FC," ".join(ctx.env.FCFLAGS+ctx.env.FCFLAGS_fc_omp)), output=waflib.Context.BOTH)
      #print "RET",llgo,llge
      L = set([ll.strip() for ll in re.findall("-L(.+)\s*\\\\", llge.split("ld ")[1]) if ("ifort" in ll.lower()) or ("intel" in ll.lower())])
      l = set([ll.strip() for ll in re.findall("-l(.+)\s*\\\\", llge.split("ld ")[1])])
      rL = set()
      rl = set()
      for Li in L:
        oli = os.listdir(Li)
        for li in l:
          if ctx.env.cshlib_PATTERN%li in oli:
            rl.add(li)
            rL.add(Li)
    except:
      ctx.end_msg(False)
      raise
    for pth in list(rL) + ["/lib","/lib64"]:
      if osp.exists(pth):
        ctx.env.append_value("LIBPATH_fc_runtime",pth)
        ctx.env.append_value("RPATH_fc_runtime",pth)
    
    ctx.env.append_value("LIB_fc_runtime",list(rl)+["pthread"])
    ctx.end_msg(True)
  show_linkline(ctx)
  ctx.env.has_ifort = True

Example 18

Project: montepython_public
Source File: try_ifort.py
View license
def ifort_conf_(ctx):
  ctx.env.FC=[]
  ctx.load('ifort')
  if sys.platform.lower()=="darwin":
    ctx.env.LINKFLAGS_fcshlib = ['-dynamiclib']
  ctx.env.append_value('FCFLAGS',ctx.env.mopt.split())
  ctx.env.append_value("FCFLAGS_fc_omp","-openmp")
  ctx.env.FCSHLIB_MARKER = [""]
  ctx.env.FCSTLIB_MARKER = [""]
  ctx.check_cc(
    errmsg="failed",msg='Compile a test code with ifort',
    mandatory=1,fragment = "program test\n  WRITE(*,*) 'hello world'\n end program test\n",compile_filename='test.f90',features='fc fcprogram')
  if not ctx.options.fortran_flagline:
    ctx.start_msg("retrieve ifort link line")
    if "/" not in ctx.env.FC:
      ctx.env.FC = ctx.cmd_and_log("which %s"%ctx.env.FC).strip()
      #print ctx.env.FC
    ifort_path = osp.dirname(osp.realpath(ctx.env.FC))
    
    #print ifort_path
    if ctx.options.m32:
      try:
        f=open(osp.join(ifort_path,'ifortvars_ia32.sh'))
      except:
        ctx.end_msg(False)
        raise Errors.WafError("Can't locate ifort configuration file")
    else:
      try:
        f=open(osp.join(ifort_path,'ifortvars_intel64.sh'))
      except:
        ctx.end_msg(False)
        raise Errors.WafError("Can't locate ifort configuration file")

    txt = f.read()
    f.close()
    #print txt
    if sys.platform.lower()=="darwin":
      sp = "DYLD_LIBRARY_PATH"
    else:
      sp = "LD_LIBRARY_PATH"
    res = re.findall("\s"+sp+"\s*=\s*\"(.+)\"",txt)[0]
    for pth in res.split(":"):
      ctx.env.append_value("LIBPATH_fc_runtime",pth)
      ctx.env.append_value("RPATH_fc_runtime",pth)
    ctx.env.append_value("LIB_fc_runtime",["ifcore","intlc","ifport","imf","irc","svml","iomp5","pthread"])
    ctx.end_msg(True)
  show_linkline(ctx)  

Example 19

Project: montepython_public
Source File: try_ifort.py
View license
def gfortran_conf(ctx):
  ctx.env.FC=[]
  ctx.env.FCFLAGS = []
  ctx.load('gfortran')
  ctx.env["FCFLAGS_fc_omp"]=[]
  ctx.env.append_value("FCFLAGS_fc_omp","-fopenmp")
  ctx.env.append_value("FCFLAGS","-DGFORTRAN")
  ctx.env.append_value("FCFLAGS","-ffixed-line-length-0")
  ctx.env.append_value("FCFLAGS","-ffree-line-length-0")
  mopt = ctx.env.mopt
  if sys.platform.lower()=="darwin":
    if "i386" in ctx.env.mopt:
      ctx.env.append_value('FCFLAGS','-m32')
      mopt = "-m32"
    else:
      ctx.env.append_value('FCFLAGS','-m64')
      mopt = "-m64"
  else:
    ctx.env.append_value('FCFLAGS',ctx.env.mopt.split())
  ctx.start_msg("Check gfortran version") 
  v90 = ctx.cmd_and_log(ctx.env.FC+" --version",quiet=Context.STDOUT).split("\n")[0].strip()
  version90 = re.findall("(4\.[0-9]\.[0-9])",v90)
  if len(version90)<1:
    #Logs.pprint("PINK","Can't get gfortran version... Let's hope for the best")
    ctx.end_msg("not found, let's hope for the best...",color="PINK")
  else:
    version90 = version90[0]
    vmid = int(version90.split(".")[1])
    if vmid<3:
      ctx.end_msg(v90,color="YELLOW")
      raise Errors.WafError("gfortran version need to be above 4.3 got %s"%version90)
    ctx.end_msg(v90)
  
  # kludge !
  ctx.env.FCSHLIB_MARKER = [""]
  ctx.env.FCSTLIB_MARKER = [mopt]
  ctx.check_cc(
      errmsg="failed",msg='Compile a test code with gfortran',
      mandatory=1,fragment = "program test\n  WRITE(*,*) 'hello world'\n end program test\n",compile_filename='test.f90',features='fc fcprogram')

  ctx.start_msg("retrieve gfortran link line")
  lgfpath = ctx.cmd_and_log(ctx.env.FC+" %s -print-file-name=libgfortran.dylib"%mopt,quiet=Context.STDOUT)    
  lpath = [osp.dirname(osp.realpath(lgfpath))]
  lgfpath = ctx.cmd_and_log(ctx.env.FC+" %s -print-file-name=libgomp.dylib"%mopt,quiet=Context.STDOUT)    
  lpath += [osp.dirname(osp.realpath(lgfpath))]
  lpath = set(lpath)

  ctx.env.append_value("LIB_fc_runtime",["gfortran","gomp"])
  ctx.env.append_value("LIBPATH_fc_runtime",list(lpath))
  ctx.env.append_value("RPATH_fc_runtime",list(lpath))
  ctx.end_msg(True)
  
  show_linkline(ctx)

Example 20

Project: PyBadUSB
Source File: __main__.py
View license
def main():
	parser = argparse.ArgumentParser(prog='python -m {}'.format(__package__))
	
	# device arguments
	if 'win' in sys.platform.lower():
		parser.add_argument('--device', default=win_device_path_default, help='Path to the device. Default is \'{}\''.format(win_device_path_default))
	elif 'linux' in sys.platform.lower():
		parser.add_argument('--device', default=linux_device_path_default, help='Path to the device. Default is \'{}\''.format(linux_device_path_default))
	else:
		parser.add_argument('device', help='Path to the device')
	
	# binary path arguments
	parser.add_argument('--firmware', default=firmware_default, help='Path to the base firmware image to inject. Default is \'{}\''.format(firmware_default))
	parser.add_argument('--burner', default=burner_default, help='Path to the burner image for the device. Default is \'{}\''.format(burner_default))
	parser.add_argument('--payload', default=payload_default, help='Path to payload to inject into firmware. Default is \'{}\''.format(payload_default))
	
	args = parser.parse_args()
	
	payload  = args.payload
	firmware = args.firmware
	burner   = args.burner
	
	# Connecting to device
	print 'Getting device..'
	
	device = badusb.get_device(phison.Phison2303, args.device)
	if not device:
		print 'Device not found!'
		exit()
	
	# Getting device information
	print 'Updating device data...'
	
	if not device.get_info():
		print 'Failed getting info!'
		device.close()
		exit()
	
	print_info(device)
	
	# Creating new firmware and injecting it to device
	print 'Embeding payload and burning it...'
	if not badusb.badusb(device, payload, firmware, burner):
		print 'Failed burning payload!'
		exit()
	
	print 'Finished!'
	device.close()

Example 21

Project: qiime
Source File: setup.py
View license
def build_SortMeRNA():
    """Download and build SortMeRNA then copy it to the scripts directory"""
    status("Building SortMeRNA...")

    # SortMeRNA's configure script doesn't correctly guess the C/C++ compilers
    # to use on OS X. Try to figure that out here.
    if sys.platform.lower() in ['darwin', 'macos']:
        cxx = 'clang++'
        cc = 'clang'
    elif sys.platform.lower() in ['linux', 'linux2']:
        cxx = 'g++'
        cc = 'gcc'
    else:
        status("Unknown or unsupported platform %r, so cannot build SortMeRNA.\n" % sys.platform)
        return

    for compiler in cxx, cc:
        if not app_available(compiler):
            status("%r not installed, so cannot build SortMeRNA.\n" % compiler)
            return

    cwd = getcwd()
    scripts = join(cwd, 'scripts')
    cxx_old = environ.get('CXX', '')
    cc_old = environ.get('CC', '')

    try:
        tempdir = mkdtemp()
        if download_file('ftp://ftp.microbio.me/pub/sortmerna-2.0-no-db.tar.gz',
                         tempdir, 'sortmerna-2.0-no-db.tar.gz'):
            status("Could not download SortMeRNA, so cannot install it.\n")
            return

        chdir(tempdir)

        if not system_call('tar xzf sortmerna-2.0-no-db.tar.gz',
                           'extract SortMeRNA archive'):
            return

        chdir('sortmerna-2.0')

        environ['CXX'] = cxx
        environ['CC'] = cc

        if not system_call('bash build.sh', 'build SortMeRNA'):
            return

        copy('sortmerna', scripts)
        copy('indexdb_rna', scripts)
        status("SortMeRNA built.\n")
    finally:
        environ['CXX'] = cxx_old
        environ['CC'] = cc_old

        # remove the source
        rmtree(tempdir)
        chdir(cwd)

Example 22

Project: taurus
Source File: proxy2jmx.py
View license
    def startup(self):
        super(Proxy2JMX, self).startup()
        self.log.info('Starting BlazeMeter recorder...')

        labels = []
        is_linux = 'linux' in sys.platform.lower()
        if is_linux:
            self.log.info('Set proxy for selenium: %s', self.proxy)
        else:
            msg = "Your system doesn't support settings of proxy by Taurus way, " \
                  "please set HTTP and HTTPS proxy to %s manually" % self.proxy
            self.log.warning(msg)

        for executor in self.engine.provisioning.executors:
            if isinstance(executor, AbstractSeleniumExecutor):
                if executor.label:
                    labels.append(executor.label)
                executor.add_env({'http_proxy': self.proxy,     # set vars anyway for case
                                  'https_proxy': self.proxy,    # linux system can't say correct name
                                  'XDG_CURRENT_DESKTOP': None,  # (it might be in Docker, etc.)
                                  'DESKTOP_SESSION': None,
                                  'GNOME_DESKTOP_SESSION_ID': None,
                                  'KDE_FULL_SESSION': None})
        if len(labels) == 1:
            self.label += '_' + labels[0]

        self.api_request('/startRecording', 'POST')

Example 23

Project: inkscape-silhouette
Source File: install_osx.py
View license
def install_inkscape_silhouette():
	try:
		logger.info("inkscape_silhouette install starting")

		# make sure this is os x
		logger.debug("making sure running on OS X")
		sys_platform = sys.platform.lower()
		logger.debug("platform: %s", sys_platform)
		if not sys_platform.startswith('darwin'):
			logger.error("Installer only works with OS X")
			return

		if not os.path.isdir(extensions_dir):
			logger.info("creating extensions dir %s", extensions_dir)
			os.makedirs(extensions_dir)

		install_prerequisites()
		install_extension()
		check_libusb()
		logger.info("inkscape_silhouette extension install ended")
	except Exception as ex:
		logger.warning("inkscape_silhouette install was unsuccessful. Please check previous messages for the cause. Details: %s", ex)

Example 24

Project: pycompat
Source File: __init__.py
View license
    def __init__(self):
        if major >= 2:
            _plat = sys.platform.lower()
        else:
            _plat = string.lower(sys.platform)

        self.is_windows = _plat == WIN_32
        self.is_cygwin = _plat == CYGWIN

        x64 = ['AMD64', 'x86_64', 'IA64']

        if major >= 2:
            self.is_linux = _plat.startswith(LINUX)
            self.is_64bits = python.is_64bits or \
                os.environ.get('PROCESSOR_ARCHITECTURE', '') in x64 or \
                os.environ.get('PROCESSOR_ARCHITEW6432', '') in x64 or \
                os.environ.get('CPU', '') in x64 or \
                os.environ.get('MACHTYPE', '').split('-')[0] in x64
        else:
            self.is_linux = string.find(_plat, LINUX) == 0
            self.is_64bits = python.is_64bits or \
                os.environ.get('PROCESSOR_ARCHITECTURE', '') in x64 or \
                os.environ.get('PROCESSOR_ARCHITEW6432', '') in x64 or \
                os.environ.get('CPU', '') in x64 or \
                string.split(os.environ.get('MACHTYPE', ''), '-')[0] in x64

        self.is_linux2 = _plat == LINUX2
        self.is_linux3 = _plat == LINUX3
        self.is_mac_os = _plat == MAC_OS_X

        self.is_32bits = not self.is_64bits

Example 25

Project: backdoorme
Source File: interactive_shell.py
View license
def interactive_open(program=None, encoding=None):
	try:
		if program is None:
			if "win" in sys.platform.lower():
				program="cmd.exe"
				encoding="cp437"
			else:
				program="/bin/sh"
				encoding=None
		print "Opening interactive %s ... (encoding : %s)"%(program,encoding)
		p = Popen([program], stdout=PIPE, stderr=PIPE, stdin=PIPE, bufsize=0, shell=True, close_fds=ON_POSIX, universal_newlines=True)
		q = Queue()
		q2 = Queue()
		t = Thread(target=write_output, args=(p.stdout, q))
		t.daemon = True
		t.start()

		t = Thread(target=write_output, args=(p.stderr, q2))
		t.daemon = True
		t.start()

		t = Thread(target=flush_loop, args=(q, encoding))
		t.daemon = True
		t.start()

		t = Thread(target=flush_loop, args=(q2, encoding))
		t.daemon = True
		t.start()

		while True:
			line = raw_input()
			p.stdin.write(line+"\n")
			if line.strip()=="exit":
				break
	except Exception as e:
		print(traceback.format_exc())

Example 26

Project: backdoorme
Source File: interactive_shell.py
View license
def interactive_open(program=None, encoding=None):
	try:
		if program is None:
			if "win" in sys.platform.lower():
				program="cmd.exe"
				encoding="cp437"
			else:
				program="/bin/sh"
				encoding=None
		print "Opening interactive %s ... (encoding : %s)"%(program,encoding)
		p = Popen([program], stdout=PIPE, stderr=PIPE, stdin=PIPE, bufsize=0, shell=True, close_fds=ON_POSIX, universal_newlines=True)
		q = Queue()
		q2 = Queue()
		t = Thread(target=write_output, args=(p.stdout, q))
		t.daemon = True
		t.start()

		t = Thread(target=write_output, args=(p.stderr, q2))
		t.daemon = True
		t.start()

		t = Thread(target=flush_loop, args=(q, encoding))
		t.daemon = True
		t.start()

		t = Thread(target=flush_loop, args=(q2, encoding))
		t.daemon = True
		t.start()

		while True:
			line = raw_input()
			p.stdin.write(line+"\n")
			if line.strip()=="exit":
				break
	except Exception as e:
		print(traceback.format_exc())

Example 27

Project: PeachPy
Source File: loader.py
View license
    def __init__(self, code_size, data_size=0):
        from peachpy.util import is_int
        if not is_int(code_size):
            raise TypeError("code size must be an integer")
        if not is_int(data_size):
            raise TypeError("data size must be an integer")
        if code_size <= 0:
            raise ValueError("code size must be positive")
        if data_size < 0:
            raise ValueError("data size must be non-negative")

        import mmap
        self.allocation_granularity = max(mmap.ALLOCATIONGRANULARITY, mmap.PAGESIZE)
        self.code_address = None
        self.code_size = self.allocation_size(code_size)
        self.data_address = None
        self.data_size = self.allocation_size(data_size)

        self._release_memory = None

        osname = sys.platform.lower()
        if osname == "darwin" or osname.startswith("linux"):
            import ctypes

            if osname == "darwin":
                libc = ctypes.cdll.LoadLibrary("libc.dylib")
            else:
                libc = ctypes.cdll.LoadLibrary("libc.so.6")

            # void* mmap(void* addr, size_t len, int prot, int flags, int fd, off_t offset)
            mmap_function = libc.mmap
            mmap_function.restype = ctypes.c_void_p
            mmap_function.argtype = [ctypes.c_void_p, ctypes.c_size_t,
                             ctypes.c_int, ctypes.c_int,
                             ctypes.c_int, ctypes.c_size_t]
            # int munmap(void* addr, size_t len)
            munmap_function = libc.munmap
            munmap_function.restype = ctypes.c_int
            munmap_function.argtype = [ctypes.c_void_p, ctypes.c_size_t]

            def munmap(address, size):
                munmap_result = munmap_function(ctypes.c_void_p(address), size)
                assert munmap_result == 0

            self._release_memory = lambda address_size: munmap(address_size[0], address_size[1])

            # Allocate code segment
            code_address = mmap_function(None, self.code_size,
                                         mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC,
                                         mmap.MAP_ANON | mmap.MAP_PRIVATE,
                                         -1, 0)
            if code_address == -1:
                raise OSError("Failed to allocate memory for code segment")
            self.code_address = code_address

            if self.data_size > 0:
                # Allocate data segment
                data_address = mmap_function(None, self.data_size,
                                             mmap.PROT_READ | mmap.PROT_WRITE,
                                             mmap.MAP_ANON | mmap.MAP_PRIVATE,
                                             -1, 0)
                if data_address == -1:
                    raise OSError("Failed to allocate memory for data segment")
                self.data_address = data_address
        elif osname == "win32":
            import ctypes

            # From WinNT.h
            PAGE_READWRITE = 0x04
            PAGE_EXECUTE_READWRITE = 0x40
            MEM_COMMIT = 0x1000
            MEM_RESERVE = 0x2000
            MEM_RELEASE = 0x8000

            # LPVOID WINAPI VirtualAlloc(LPVOID address, SIZE_T size, DWORD allocationType, DWORD protect)
            VirtualAlloc_function = ctypes.windll.kernel32.VirtualAlloc
            VirtualAlloc_function.restype = ctypes.c_void_p
            VirtualAlloc_function.argtype = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_ulong, ctypes.c_ulong]
            # BOOL WINAPI VirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD  dwFreeType)
            VirtualFree_function = ctypes.windll.kernel32.VirtualFree
            VirtualFree_function.restype = ctypes.c_int
            VirtualFree_function.argtype = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_ulong]

            def VirtualFree(address, size):
                VirtualFree_result = VirtualFree_function(address, size, MEM_RELEASE)
                assert VirtualFree_result != 0

            self._release_memory = lambda address_size: VirtualFree(address_size[0], address_size[1])

            # Allocate code segment
            code_address = VirtualAlloc_function(None, self.code_size,
                                                 MEM_RESERVE | MEM_COMMIT,
                                                 PAGE_EXECUTE_READWRITE)
            if not code_address:
                raise OSError("Failed to allocate memory for code segment")
            self.code_address = code_address

            if self.data_size > 0:
                # Allocate data segment
                data_address = VirtualAlloc_function(None, self.data_size,
                                                     MEM_RESERVE | MEM_COMMIT,
                                                     PAGE_READWRITE)
                if not data_address:
                    raise OSError("Failed to allocate memory for data segment")
                self.data_address = data_address
        elif osname == "nacl":
            import dynacl

            # Allocate code segment
            self.allocation = dynacl.allocate(self.code_size, self.data_size)
            self.code_address = self.allocation.code_address
            self.data_address = self.allocation.data_address
            self.copy_code = self._nacl_copy_code
        else:
            raise ValueError("Unknown host OS: " + osname)

Example 28

Project: PeachPy
Source File: loader.py
View license
    def __init__(self, code_size, data_size=0):
        from peachpy.util import is_int
        if not is_int(code_size):
            raise TypeError("code size must be an integer")
        if not is_int(data_size):
            raise TypeError("data size must be an integer")
        if code_size <= 0:
            raise ValueError("code size must be positive")
        if data_size < 0:
            raise ValueError("data size must be non-negative")

        import mmap
        self.allocation_granularity = max(mmap.ALLOCATIONGRANULARITY, mmap.PAGESIZE)
        self.code_address = None
        self.code_size = self.allocation_size(code_size)
        self.data_address = None
        self.data_size = self.allocation_size(data_size)

        self._release_memory = None

        osname = sys.platform.lower()
        if osname == "darwin" or osname.startswith("linux"):
            import ctypes

            if osname == "darwin":
                libc = ctypes.cdll.LoadLibrary("libc.dylib")
            else:
                libc = ctypes.cdll.LoadLibrary("libc.so.6")

            # void* mmap(void* addr, size_t len, int prot, int flags, int fd, off_t offset)
            mmap_function = libc.mmap
            mmap_function.restype = ctypes.c_void_p
            mmap_function.argtype = [ctypes.c_void_p, ctypes.c_size_t,
                             ctypes.c_int, ctypes.c_int,
                             ctypes.c_int, ctypes.c_size_t]
            # int munmap(void* addr, size_t len)
            munmap_function = libc.munmap
            munmap_function.restype = ctypes.c_int
            munmap_function.argtype = [ctypes.c_void_p, ctypes.c_size_t]

            def munmap(address, size):
                munmap_result = munmap_function(ctypes.c_void_p(address), size)
                assert munmap_result == 0

            self._release_memory = lambda address_size: munmap(address_size[0], address_size[1])

            # Allocate code segment
            code_address = mmap_function(None, self.code_size,
                                         mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC,
                                         mmap.MAP_ANON | mmap.MAP_PRIVATE,
                                         -1, 0)
            if code_address == -1:
                raise OSError("Failed to allocate memory for code segment")
            self.code_address = code_address

            if self.data_size > 0:
                # Allocate data segment
                data_address = mmap_function(None, self.data_size,
                                             mmap.PROT_READ | mmap.PROT_WRITE,
                                             mmap.MAP_ANON | mmap.MAP_PRIVATE,
                                             -1, 0)
                if data_address == -1:
                    raise OSError("Failed to allocate memory for data segment")
                self.data_address = data_address
        elif osname == "win32":
            import ctypes

            # From WinNT.h
            PAGE_READWRITE = 0x04
            PAGE_EXECUTE_READWRITE = 0x40
            MEM_COMMIT = 0x1000
            MEM_RESERVE = 0x2000
            MEM_RELEASE = 0x8000

            # LPVOID WINAPI VirtualAlloc(LPVOID address, SIZE_T size, DWORD allocationType, DWORD protect)
            VirtualAlloc_function = ctypes.windll.kernel32.VirtualAlloc
            VirtualAlloc_function.restype = ctypes.c_void_p
            VirtualAlloc_function.argtype = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_ulong, ctypes.c_ulong]
            # BOOL WINAPI VirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD  dwFreeType)
            VirtualFree_function = ctypes.windll.kernel32.VirtualFree
            VirtualFree_function.restype = ctypes.c_int
            VirtualFree_function.argtype = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_ulong]

            def VirtualFree(address, size):
                VirtualFree_result = VirtualFree_function(address, size, MEM_RELEASE)
                assert VirtualFree_result != 0

            self._release_memory = lambda address_size: VirtualFree(address_size[0], address_size[1])

            # Allocate code segment
            code_address = VirtualAlloc_function(None, self.code_size,
                                                 MEM_RESERVE | MEM_COMMIT,
                                                 PAGE_EXECUTE_READWRITE)
            if not code_address:
                raise OSError("Failed to allocate memory for code segment")
            self.code_address = code_address

            if self.data_size > 0:
                # Allocate data segment
                data_address = VirtualAlloc_function(None, self.data_size,
                                                     MEM_RESERVE | MEM_COMMIT,
                                                     PAGE_READWRITE)
                if not data_address:
                    raise OSError("Failed to allocate memory for data segment")
                self.data_address = data_address
        elif osname == "nacl":
            import dynacl

            # Allocate code segment
            self.allocation = dynacl.allocate(self.code_size, self.data_size)
            self.code_address = self.allocation.code_address
            self.data_address = self.allocation.data_address
            self.copy_code = self._nacl_copy_code
        else:
            raise ValueError("Unknown host OS: " + osname)

Example 29

Project: quaternion
Source File: __init__.py
View license
def calculate_version():
    from sys import platform
    on_windows = ('win' in platform.lower() and not 'darwin' in platform.lower())
    use_shell = not on_windows
    try:
        git_revision = subprocess.check_output("""git show -s --format="%ci %h" HEAD""", shell=use_shell).decode('ascii').rstrip()
        date, time, utc_offset, short_hash = git_revision.split(' ')
        date = date.replace('-', '.').strip()  # make date an acceptable version string
        short_hash = short_hash.strip()  # remove newline and any other whitespace
        short_hash = int(short_hash, 16)  # So that it's a valid PEP 440 version identifier
        dirty = bool(subprocess.call("git diff-files --quiet --", shell=use_shell))
        dirty = dirty or bool(subprocess.call("git diff-index --cached --quiet HEAD --", shell=use_shell))
        version = '{0}.dev{1}'.format(date, short_hash)
        if dirty:
            version += '+dirty'
        exec('putative__version__ = "{0}"'.format(version))  # see if this will raise an error for some reason
    except Exception as e:
        # If any of the above failed for any reason whatsoever, fall back on this dumb version, unless we're on a CI
        from os import getenv
        print('\nThe `calculate_version` function failed to get the git version.')
        print('Maybe your version of python (<2.7?) is too old.  Here\'s the exception:')
        print(e)
        if getenv('CI') is not None:
            if getenv('CI').lower() == 'true':
                print('Raising exception because environment variable `CI` is "{0}"'.format(getenv('CI')))
                raise e
        print('This should not be a problem, unless you need an accurate version number.')
        print('Continuing on, in spite of it all...\n')
        from datetime import datetime
        date = datetime.now().isoformat().split('T')[0]
        date = date.replace('-', '.').strip()
        version = '0.0.0.dev' + date
    return version

Example 30

Project: quaternion
Source File: __init__.py
View license
def calculate_version():
    from sys import platform
    on_windows = ('win' in platform.lower() and not 'darwin' in platform.lower())
    use_shell = not on_windows
    try:
        git_revision = subprocess.check_output("""git show -s --format="%ci %h" HEAD""", shell=use_shell).decode('ascii').rstrip()
        date, time, utc_offset, short_hash = git_revision.split(' ')
        date = date.replace('-', '.').strip()  # make date an acceptable version string
        short_hash = short_hash.strip()  # remove newline and any other whitespace
        short_hash = int(short_hash, 16)  # So that it's a valid PEP 440 version identifier
        dirty = bool(subprocess.call("git diff-files --quiet --", shell=use_shell))
        dirty = dirty or bool(subprocess.call("git diff-index --cached --quiet HEAD --", shell=use_shell))
        version = '{0}.dev{1}'.format(date, short_hash)
        if dirty:
            version += '+dirty'
        exec('putative__version__ = "{0}"'.format(version))  # see if this will raise an error for some reason
    except Exception as e:
        # If any of the above failed for any reason whatsoever, fall back on this dumb version, unless we're on a CI
        from os import getenv
        print('\nThe `calculate_version` function failed to get the git version.')
        print('Maybe your version of python (<2.7?) is too old.  Here\'s the exception:')
        print(e)
        if getenv('CI') is not None:
            if getenv('CI').lower() == 'true':
                print('Raising exception because environment variable `CI` is "{0}"'.format(getenv('CI')))
                raise e
        print('This should not be a problem, unless you need an accurate version number.')
        print('Continuing on, in spite of it all...\n')
        from datetime import datetime
        date = datetime.now().isoformat().split('T')[0]
        date = date.replace('-', '.').strip()
        version = '0.0.0.dev' + date
    return version

Example 31

Project: OpenCobolIDE
Source File: system.py
View license
def get_system_infos():
    from open_cobol_ide import __version__
    from open_cobol_ide.compilers import GnuCobolCompiler
    from pyqode.qt import QtCore
    import pyqode.core
    import pyqode.cobol
    import pygments

    try:
        import qdarkstyle
    except ImportError:
        qdarkstyle_version = 'Not installed'
    else:
        qdarkstyle_version = qdarkstyle.__version__

    def get_linux_distro():
        try:
            out = str(subprocess.check_output(['lsb_release', '-i']),
                      locale.getpreferredencoding())
        except OSError:
            distro = platform.linux_distribution()[0]
            if not distro:
                distro = 'linux distribution not found'
        else:
            distro = out.split(':')[1].strip()
        return distro

    system_info = platform.system()
    if 'linux' in sys.platform.lower():
        system_info = get_linux_distro()
    elif 'darwin' in sys.platform.lower():
        system_info = 'Mac OS X %s' % platform.mac_ver()[0]
    return '\n'.join([
        'Operating System: %s' % system_info,
        'OpenCobolIDE: %s' % __version__,
        'GnuCOBOL: %s' % GnuCobolCompiler().get_version(
            include_all=False),
        'Python: %s (%dbits)' % (platform.python_version(), 64
                                 if sys.maxsize > 2**32 else 32),
        'Qt: %s' % QtCore.QT_VERSION_STR,
        'PyQt: %s' % QtCore.PYQT_VERSION_STR,
        'pyqode.core: %s' % pyqode.core.__version__,
        'pyqode.cobol: %s' % pyqode.cobol.__version__,
        'pyqode.qt: %s' % pyqode.qt.__version__,
        'pygments: %s' % pygments.__version__,
        'QDarkStyle: %s' % qdarkstyle_version
    ])