Beispiel #1
0
def reg_query(keyname, value=None):
    if os.name != "nt":
        return []

    blanklines = 1
    
    if value == None:
        tempresult = os.popen2("reg.exe query \"%s\"" % keyname)
    else:
        tempresult = os.popen2("reg.exe query \"%s\" /v \"%s\"" % (keyname, value))
    stdout = tempresult[1]
    stdout = stdout.readlines()

    # handle case when reg.exe isn't in path
    if len(stdout) == 0:
        if value == None:
            tempresult = os.popen2(os.environ["WINDIR"] + "\\system32\\reg.exe query \"%s\"" % keyname)
        else:
            tempresult = os.popen2(os.environ["WINDIR"] + "\\system32\\reg.exe query \"%s\" /v \"%s\"" % (keyname, value))
        stdout = tempresult[1]
        stdout = stdout.readlines()

    # For Windows XP, this was changed in Vista!
    if len(stdout) > 0 and stdout[1].startswith("! REG.EXE"):
        blanklines += 2
        if value == None:
            blanklines += 2

    stdout = stdout[blanklines:]
    
    return stdout
def convert(*args):
	'''
	Convert chosen files into xpm.
	'''	
	# Grab the path from the ScrollField
	targetPath = cmds.scrollField( "mecCVTDir", q=True, text=True)
	
	# Grabbing the selected elements from the textScrollList
	tslSel = cmds.textScrollList("mecCVTTSL", q=True, si=True)
	
	# - Checking to see if anything is selcted in the textScrollList
	#   if nothing is selected grab everything.
	if( not(tslSel) ):
		print("Nothing selected in textScrollList Selected.\n Converting everything.")
		tslSel = cmds.textScrollList("mecCVTTSL", q=True, ai=True)

	
	for tsl in tslSel:
		# Creating the proper path to the files.
		# split file up to get the file name with out the extension.
		baseFile = tsl.split(".")[0]
		destFile = '"' + targetPath + "/""" + baseFile + '.xpm"'
		
		sourceFile = '"' + targetPath + "/" + tsl + '"'
		
		# Switching from front slashes to backslashes if on a windows machine.
		if(cmds.about(os=True) == "nt"):
			destFile = convertSlashes( destFile )
			sourceFile = convertSlashes( sourceFile )
			
		# Compiling the command line to convert the images.
		runLine = 'imconvert ' + sourceFile + " " + destFile
		print(runLine)
		# Executing the imconvert program from the command prompt (DOS)
		os.popen2(runLine)
Beispiel #3
0
def motion(accData):
    print accData['z']
    #WiimoteSensitivityDelay += 1
    if accData['z'] > 220:
        print "cambiando slide"
        os.popen2("xsendkeycode "+str(codeR)+" 1")
        os.popen2("xsendkeycode "+str(codeR)+" 0")
 def installbtnClicked(self):
     target = self.ui.targetbox.currentText()
     grubpart = self.ui.grubbox.currentText()
     homepart = self.ui.homebox.currentText()
     pwd = self.ui.rootpw1.text()
     user = self.ui.username.text()
     userpwd = self.ui.userpw1.text()
     if target.length() != 0:
         print "Targetpartition: " + target + "\nGrubpartition: " + grubpart + "\nHomepartition: " + homepart + "\nRootpw: " + pwd + "\nUsername: "******"\nUserpw: " + userpwd
         popen("mkdir -p /tmp/neptune-installer/")
         popen("echo '" + str(pwd) + "' > /tmp/neptune-installer/tmp.pwd") 
         popen("echo '" + str(user) +"' > /tmp/neptune-installer/tmp.user")
         popen("echo '" + str(userpwd) + "' > /tmp/neptune-installer/tmp.userpwd")
         popen("echo '" + str(target) + "' > /tmp/neptune-installer/tmp.hd")
         if homepart != QtGui.QApplication.translate("MainWindow", "same as target", None, QtGui.QApplication.UnicodeUTF8):
             popen("echo '" + str(homepart) + "' > /tmp/neptune-installer/tmp.home")
         if grubpart != "MBR/EFI":
             popen("echo '" + str(grubpart) + "' > /tmp/neptune-installer/tmp.grubpart")
         # Disabled for debugging
         if path.exists("/usr/bin/kdialog"):
             print "kdialog available"
             popen("kdesudo /usr/bin/neptune-install.sh &") # 2>&1 | tee -i /tmp/neptune-installer.log &")
         else:
             print "kdialog not available"
             popen2("xhost + && xterm -e '/usr/bin/neptune-install.sh'") # 2>&1 | tee -i /tmp/neptune-installer.log' ")
         sys.exit(0)
     else:
         QtGui.QMessageBox.critical(self, "No Target", self.tr("You need to enter a target for installation"),QtGui.QMessageBox.Ok)
 def soundStart(self):  
     if sys.platform[:5] == 'linux':  
         import os
         os.popen2('aplay -q' + 'done.wav')
     else:  
         import winsound
         winsound.PlaySound('done.wav', winsound.SND_FILENAME)
Beispiel #6
0
 def on_openoffice(self, action):
     doc = self.window.get_active_document()
     filename = doc.get_uri_for_display()[:-4]
     pd = restpluginDir
     os.popen2('python %s/to_odt.py --add-syntax-highlighting '
               '--stylesheet=%s/default.odt "%s.rst" "%s.odt"' %
               (pd, pd, filename, filename))
 def onAnswering(self):  
     if sys.platform[:5] == 'linux':  
         import os
         os.popen2('aplay -q' + 'music.wav')
     else:  
         import winsound
         winsound.PlaySound('music.wav', winsound.SND_FILENAME)
Beispiel #8
0
def run_jgraph(input_str, base_filename):

    jgr_file = open("%s.jgr" % base_filename, "w")
    jgr_file.write(input_str)
    jgr_file.close()

    # generate .eps (ghostview-able)
    (in_file, out_file) = os.popen2("jgraph")
    in_file.write(input_str)
    in_file.close()

    eps_file = open("%s.eps" % base_filename, "w")
    eps_file.writelines(out_file.readlines())
    eps_file.close()
        
    # generate .ps (lpr-able)
    (in_file, out_file) = os.popen2("jgraph -P")
    in_file.write(input_str)
    in_file.close()

    ps_file = open("%s.ps" % base_filename, "w")
    ps_file.writelines(out_file.readlines())
    ps_file.close()

    # generate .pdf
    os.system("ps2pdf %s.ps" % base_filename)
Beispiel #9
0
 def on_html(self, action):
     doc = self.window.get_active_document()
     filename = doc.get_uri_for_display()[:-4]
     pd = restpluginDir
     os.popen2('python %s/to_html.py --stylesheet=%s/restmain.css '
               '"%s.rst" "%s.html"' %
               (pd, pd, filename, filename))
Beispiel #10
0
def playSound():
    if sys.platform[:5] == 'linux':
        import os
        os.popen2('aplay -q' + soundFile)
    else:
        import winsound
        winsound.PlaySound(soundFile, winsound.SND_FILENAME)
Beispiel #11
0
def PlayVoiceFunction():
    #get recent download file
    try:
        fp=open(ProgramPath+'/store/recent_download.txt','r')
        StoragePath=fp.readline()
        if StoragePath[len(StoragePath)-1]=='\n':
            StoragePath=StoragePath[:len(StoragePath)-1]
        fp.close()
    except:
        UpdateStation("Please download at least one file.")
    else:
        #play voice
        if os.path.isfile(StoragePath):
            UpdateStation("Begin to play recent download file.")
            if sys.platform[:5]=="linux":
                os.popen2('aplay -q \"%s\"'%StoragePath)
                UpdateStation("Finish playing")
            elif sys.platform=='darwin':
                os.system('afplay \"%s\"'%StoragePath)
                UpdateStation("Finish playing")
            elif sys.platform[:3]=='win':
                StoragePathWin=StoragePath.replace('/','\\')
                os.system('start \"Play Google Voice\" \"%s\"'%StoragePathWin)
            #    WindowsPlayVoice(StoragePath)
        else:
            UpdateStation("You haven't download file.")
Beispiel #12
0
def ngram(words, outputf):
    ngramf = open('lmdict/tempngram00.train', 'w')
    for word in words:
        ngramf.write('%s ' % word)
    ngramf.close()

    os.popen2('estimate-ngram -s FixKN -t lmdict/tempngram00.train -wl lmdict/%s.arpa' % outputf)
Beispiel #13
0
	def __init__(self):
		if hasprefix():
			self.filtin1, self.filtout1 = os.popen2('c++filt --strip-underscore', 'rw')
			self.filtin2, self.filtout2 = os.popen2('c++filt --no-strip-underscore', 'rw')
		else:
			self.filtin1, self.filtout1 = os.popen2('c++filt --no-strip-underscore', 'rw')
			self.filtin2, self.filtout2 = os.popen2('c++filt --strip-underscore', 'rw')
Beispiel #14
0
def start_dump(host, port):
    # Start up tcpdump pushing data into netcat on the sql server
    interface = "eth0"
    
    # Start up tcpdump pushing data into netcat on the sql server
    SRC_DUMP_CMD = "ssh root@%s '/usr/sbin/tcpdump -p -n -s 0 -w - -i %s dst port 3306 or src port 3306 | nc %s %d'" \
                   % (host, interface, socket.getfqdn(), port)
    os.popen2(SRC_DUMP_CMD, "r")
Beispiel #15
0
 def OnButtonmodifyButton(self, event):
     '''修改数据'''   
     #打开data目录下的“自选条件.txt”
     if wx.Platform == '__WXMSW__': #windows
         os.startfile(u'data/自选条件.txt')
     else: #linux
         os.popen2(u'gedit data/自选条件.txt')
     
     event.Skip()
Beispiel #16
0
def backuptree(directory, backup):
    input, output = os.popen2('find %s -type d' %directory)
    dir = output.readline().strip()
    while dir:
        makepaths(join(backup, dir))
        dir = output.readline().strip()
    input, output = os.popen2('find %s -type f' %directory)
    file = output.readline().strip()
    while file:
        os.link(file, join(backup, file))
        file = output.readline().strip()
Beispiel #17
0
    def test_os_popen2(self):
        # same test as test_popen2(), but using the os.popen*() API
        if os.name == 'posix':
            w, r = os.popen2([self.cmd])
            self.validate_output(self.teststr, self.expected, r, w)

            w, r = os.popen2(["echo", self.teststr])
            got = r.read()
            self.assertEquals(got, self.teststr + "\n")

        w, r = os.popen2(self.cmd)
        self.validate_output(self.teststr, self.expected, r, w)
Beispiel #18
0
def update_packages (text_files, bin_files, stage_dir, package_dir):
    import os

    print "Updating packages...."
    os.chdir (stage_dir)

    # -g appends, -q for quiet operation
    zip_base_args = " -gqu "
    # -l causes line ending conversion for windows
    zip_text_args = " -l "
    zip_file = stage_dir + "/zip-archive.zip"

    # -r appends, -f specifies file.
    tar_args = "-uf "
    tar_file = stage_dir + "/tar-archive.tar"

    # Zip binary files
    print "\tAdding binary files to zip...."
    instream, outstream = os.popen2 ("xargs zip " + zip_base_args + zip_file)

    instream.write (bin_files)

    instream.close ()
    outstream.close ()

    # Need to wait for zip process spawned by popen2 to complete
    # before proceeding.
    os.wait ()

    print "\tAdding text files to zip....."
    instream, outstream = os.popen2 ("xargs zip " + zip_base_args + zip_text_args + zip_file)

    instream.write (text_files)

    instream.close ()
    outstream.close ()

    # Need to wait for zip process spawned by popen2 to complete
    # before proceeding.
    os.wait ()

    # Tar files
    print "\tAdding to tar file...."
    instream, outstream = os.popen2 ("xargs tar " + tar_args + tar_file)

    instream.write (' ' + bin_files + ' ' + text_files)

    instream.close ()
    outstream.close ()

    os.wait ()
Beispiel #19
0
def minify(content, type):
    minifier = MINIFY[type]
    if '%(file)s' in minifier:
        path('tmp').write_bytes(content)
        stdin, stdout = os.popen2(minifier % dict(file='tmp'))
    else:
        stdin, stdout = os.popen2(minifier)
        stdin.write(content)
    stdin.close()
    content = stdout.read()
    stdout.close()
    if '%(file)s' in minifier:
        path('tmp').remove()
    return content
Beispiel #20
0
def set_wallpaper(filename):
    import gconf
    """Sets the wallpaper to the given filename."""
    use = config.get('webilder.wallpaper_set_method')
    if use == "gnome3":
        script = ('gsettings set org.gnome.desktop.background picture-uri '
                  'file://"%s"' % filename)
        os.popen2(script)
    elif use == "gnome":
        conf_client = gconf.client_get_default()
        conf_client.set_string('/desktop/gnome/background/picture_filename',
            filename)
    elif use == "kde":
        script = 'dcop kdesktop KBackgroundIface setWallpaper "%f" 4'
        script = script.replace('%f', filename)
        os.popen2(script)
    elif use == "xfce":
        script = ('xfconf-query -c xfce4-desktop '
                  '-p /backdrop/screen0/monitor0/image-path -s "%f"')
        script = script.replace('%f', filename)
        os.popen2(script)
    elif use == "compiz_wallpaper":
        set_compiz_wallpaper(filename)
    elif use == "script":
        script = config.get('webilder.wallpaper_script')
        script = script.replace('%f', filename)
        os.popen2(script)
    stats = config.get('webilder.stats')
    stats['rotations'] += 1
    config.set('webilder.stats', stats)
    config.save_config()
Beispiel #21
0
    def __init__(self, host, port):
        
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        for i in [1,2]:
            try:
                self.sock.connect((host, port))
                break
            except:
                path = os.path.dirname(os.path.realpath(__file__))
                path = os.path.join(path, 'vuirpc/vuirpc_server')
                os.popen2(path)
                time.sleep(1)

        self.buf = ""
Beispiel #22
0
def popen2(cmd, mode="t", bufsize=_marker):
    try:
        import subprocess
        kwargs = {"stdin": subprocess.PIPE,
                  "stdout": subprocess.PIPE}
        if bufsize is not _marker:
            kwargs["bufsize"] = bufsize
        pipes = subprocess.Popen(cmd, shell=True, **kwargs)
        return pipes.stdin, pipes.stdout
    except ImportError:
        import os
        if bufsize is _marker:
            return os.popen2(cmd, mode)
        else:
            return os.popen2(cmd, mode, bufsize)
Beispiel #23
0
def test_threading_waits_for_thread_exit():
    import os
    from iptest.process_util import launch
    f = file('temp.py', 'w+')
    try:
        f.write("""
import sys
def f():
    print 'bye bye'

def f(*args):
    print 'bye bye'

sys.exitfunc = f
from threading import Thread
def count(n):
    while n > 0:
            n -= 1
    print 'done'

t1 = Thread(target=count, args=(50000000,))
t1.start()
    """)
        f.close()
        stdin, stdout = os.popen2(sys.executable +  ' temp.py')
        Assert('bye bye\n' in list(stdout))
    finally:
        import nt
        nt.unlink('temp.py')
Beispiel #24
0
def detect_number_of_cores():
    """
    detect_number_of_cores()

    Detect the number of cores in this system.

    Returns
    -------
    out : int
        The number of cores in this system.

    """
    # Linux, Unix and MacOS:
    if hasattr(os, "sysconf"):
        if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
            # Linux & Unix:
            ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
            if isinstance(ncpus, int) and ncpus > 0:
                return ncpus
        else:  # OSX:
            return int(os.popen2("sysctl -n hw.ncpu")[1].read())
    # Windows:
    if "NUMBER_OF_PROCESSORS" in os.environ:
        ncpus = int(os.environ["NUMBER_OF_PROCESSORS"])
        if ncpus > 0:
            return ncpus
    return 1  # Default
Beispiel #25
0
def IterShellCommandOutput(cmd, stdin_string=None):
  """Runs a command in a sub-process, and iterates the lines in its STDOUT.

  Args:

    cmd:           The shell command.
    stdin_string:  The string to be fed to the STDIN of the sub-process;
                   If None, the sub-process will inherit the STDIN
                   from the parent process.
  """

  # Spawns cmd in a sub-process, and gets its standard I/O file objects.
  stdin_file, stdout_file = os.popen2(cmd, 'b')

  # If the caller didn't specify a string for STDIN, gets it from the
  # parent process.
  if stdin_string is None:
    stdin_string = sys.stdin.read()

  # Feeds the STDIN string to the sub-process.
  stdin_file.write(stdin_string)
  stdin_file.close()

  while True:
    line = stdout_file.readline()
    if not line:  # EOF
      stdout_file.close()
      break

    yield line
Beispiel #26
0
Datei: bta.py Projekt: jfmc/logen
def run_bta(filename,output, annfile=None, norm='term',profile=False):
    print "Running Bta..."

    #either use exe or save state...
    cmdline = get_bta_cmd()
    
    command = "%s %s -a -norm %s -o %s -i %s -gui" % (cmdline,filename,norm,output,annfile)
                                                            
    #os.system(command)
    time = 0
    iterations = 0
    lines = os.popen2(command)[1].readlines()
    time = 0
    for i in lines:
        #debug
        print i,
        timetaken = totaltime.search(i)
        if timetaken != None:
            time = timetaken.groups()[0]
            iterations = timetaken.groups()[1]
            print "Time:",time

            break
        
    return (lines,time,iterations)
Beispiel #27
0
            def getfreespace(path):
                try:
                    mystdin, mystdout = os.popen2(u'dir "' + path + u'"')
                    sizestring = '0'
                    for line in mystdout:
                        line = line.strip()
                        index = line.rfind('bytes free')
                        if index > -1 and line[index:] == 'bytes free':
                            parts = line.split(' ')
                            if len(parts) > 3:
                                part = parts[-3]
                                part = part.replace(',', '')
                                sizestring = part
                                break

                    size = long(sizestring)
                    if size == 0L:
                        print >> sys.stderr, "getfreespace: can't determine freespace of ", path
                        for line in mystdout:
                            print >> sys.stderr, line

                        size = 1208925819614629174706176L
                except:
                    size = 1208925819614629174706176L

                return size
Beispiel #28
0
def tail(fname, n):
    exit_if_file_does_not_exist(fname)
    stdin, stdout = os.popen2("tail -n " + str(n) + " " + fname)
    stdin.close()
    lines = stdout.readlines()
    stdout.close()
    return lines
def main():
    apt_cmd = "apt-get -y --force-yes install "

    gcin_text = "gcin \"由台灣網友開發的輸入法,有許多在地化的調校,\n是在臺灣相當受到歡迎的中文輸入法。\n有許多方便的功能,穩定而強大,內建多種輸入法,\n包括功能類似微軟新注音的詞音輸入法、並「可支援無蝦米」。\n但和 Windows 下常見的操作習慣相差不少,新手可能會很不習慣。\n\""
    scim_text = "scim \"Ubuntu 預設的中文輸入法,可以輸入多國文字,功能強大,\n操作和 Windows 上接近,內含類似新注音,相當知名的新酷音輸入法,\n但是比較龐大,目前穩定性也不及 gcin\n\""
    dialog_text = "--text=下列是最常見的二種中文輸入法,'請選擇您喜好的輸入法,\n若您無法決擇,建議可以考慮 gcin:\n'"
    zenity_cmd = Template("zenity --width=512 --height=480 --list --title='選擇輸入法' --column='名稱' --column='敘述' $dialog_text $gcin $scim").substitute(gcin=gcin_text, scim=scim_text, dialog_text=dialog_text)

    fin, fout = os.popen2(zenity_cmd)
    selected_cin = fout.read().strip()

    os.system(apt_cmd + "im-switch")

    if selected_cin == 'gcin' or selected_cin == 'scim':
        os.system(apt_cmd + selected_cin)

        if selected_cin == "scim":
            os.system(apt_cmd + "scim-qtimm scim-chewing")
        elif selected_cin == 'gcin':
            os.system(apt_cmd +'gcin-qt3-immodule' )
            # install noseeing
            # FIXME: 使用者應該可以選擇不要安裝無蝦米
            #os.system( 'noseeing-inst' )
            noseeing_yes_no()

        user_scope(selected_cin)
Beispiel #30
0
def voip_play2(s1,**kargs):
    dsp,rd = os.popen2("sox -t .ul -c 2 - -t ossdsp /dev/dsp")
    def play(pkt,last=[]):
        if not pkt:
            return 
        if not pkt.haslayer(UDP):
            return 
        ip=pkt.getlayer(IP)
        if s1 in [ip.src, ip.dst]:
            if not last:
                last.append(pkt)
                return
            load=last.pop()
            x1 = load.load[12:]
#            c1.write(load.load[12:])
            if load.getlayer(IP).src == ip.src:
                x2 = ""
#                c2.write("\x00"*len(load.load[12:]))
                last.append(pkt)
            else:
                x2 = pkt.load[:12]
#                c2.write(pkt.load[12:])
            dsp.write(merge(x1,x2))
            
    sniff(store=0, prn=play, **kargs)
Beispiel #31
0
def partition_disk(dump, device):
    i, o = os.popen2('sfdisk %s' % device)
    i.write(dump)
    i.close()