def check_source_md5(self, filename): if self.is_installed: sourcedir = Popen(["rpm", "-E", '%_sourcedir'], stdout=subprocess.PIPE).stdout.read()[:-1] # replace %{name} by the specname package_name = Popen( ["rpm", "-qp", self.filename, '--qf', '%{name}'], stdout=subprocess.PIPE).stdout.read() sourcedir = sourcedir.replace("%{name}", package_name) sourcedir = sourcedir.replace("%name", package_name) src_files = glob.glob(sourcedir + '/*') # src_files = glob.glob(os.path.expanduser('~/rpmbuild/SOURCES/*')) if src_files: for name in src_files: if filename and os.path.basename( filename) != os.path.basename(name): continue self.log.debug("Checking md5 for %s" % name) sum, file = self._md5sum(name) return sum else: print('no sources found in install SRPM') return "ERROR" else: print "SRPM is not installed" return "ERROR"
def encrypt(text): encryption_password = weechat.config_get_plugin("encryption_password") # decrypt the password if it is stored as secured data if encryption_password.startswith("${sec."): encryption_password = weechat.string_eval_expression(encryption_password, {}, {}, {}) if PY3: text = text.encode("UTF-8") command="openssl enc -aes-128-cbc -salt -base64 -md md5 -A -pass env:OpenSSLEncPW" opensslenv = os.environ.copy(); # Unknown whether the encryption password should or should not be # (UTF8-)encoded before being passed to the environment in python 3. opensslenv['OpenSSLEncPW'] = encryption_password output, errors = Popen(shlex.split(command), stdin=PIPE, stdout=PIPE, stderr=PIPE,env=opensslenv).communicate(text + b" ") output = output.replace(b"/", b"_") output = output.replace(b"+", b"-") output = output.replace(b"=", b"") if PY3: output = output.decode("UTF-8") return output
def get_source_dir(self): sourcedir= Popen(["rpm", "-E", '%_sourcedir' ], stdout=subprocess.PIPE).stdout.read()[:-1] # replace %{name} by the specname package_name = Popen(["rpm", "-qp", self.filename, '--qf', '%{name}' ], stdout=subprocess.PIPE).stdout.read() sourcedir = sourcedir.replace("%{name}", package_name) sourcedir = sourcedir.replace("%name", package_name) return sourcedir
def launch(app, mon, in_new_wks): if '-cd' in app: xcwd = Popen('xcwd', stdin=PIPE, stdout=PIPE).communicate()[0] # TODO: replace all possible special characters xcwd = xcwd.replace('\n', '') special_chars = [' ', '(', ')'] for c in special_chars: xcwd = xcwd.replace(c, r'\{0}'.format(c)) app = '"' + app + ' ' + xcwd + '"' if not in_new_wks and ( mon == 'all' or mon == utils.get_current_output()): # open on the current workspace a = action.Action() a.add(action.Action.exec_, (app,)) action.default_mode(a) i3.subscribe('window', 'new', utils.set_window_mark_callback, lambda: a.process()) if not in_new_wks and ( mon != 'all' and mon != utils.get_current_output()): # open on the visible workspace on another output otherw = utils.get_current_workspace(mon) a = action.Action() a.add(action.Action.jump_to_workspace, (otherw,)) a.add(action.Action.exec_, (app,)) action.default_mode(a) i3.subscribe('window', 'new', utils.set_window_mark_callback, lambda: a.process()) elif in_new_wks and ( mon == 'all' or mon == utils.get_current_output()): # new workspace on the current output neww = utils.get_free_workspaces()[0] a = action.Action() a.add(action.Action.jump_to_workspace, (neww,)) a.add(action.Action.exec_, (app,)) action.default_mode(a) i3.subscribe('window', 'new', utils.set_window_mark_callback, lambda: a.process()) elif in_new_wks and ( mon != 'all' and mon != utils.get_current_output()): # new workspace on another output neww = utils.get_free_workspaces()[0] a = action.Action() a.add(action.Action.focus_output, (mon,)) a.add(action.Action.jump_to_workspace, (neww,)) a.add(action.Action.exec_, (app,)) action.default_mode(a) i3.subscribe('window', 'new', utils.set_window_mark_callback, lambda: a.process())
def Question(a, syntax, ret, bOtherQuestion, bWhen, bWhy, bHowMany, bWhat, bHow, bPlan, MaxResults=100, MaxDepth=100): rs = Popen( 'swipl -q -f MOM_pl.pl', shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT).communicate( "leash(-all)," + ("trace," if not bPlan else "") + ret.split("A")[1] + "." + (("\n;".join("" for z in range(MaxResults)) ) if bHow == False and bPlan == False else ""))[0].replace( "\r", "") ReasWHEN = set([]) ReasWHY = set([]) Ansli = set([]) M = ["Call:", "Fail:", "Exit:", "Redo:"] for l in M: rs = rs.replace(l, "\n" + l) for a in rs.split( "\n" ): #read the proof, succeeded goals in the reason predicate list are reasons, in answer mode add answers if "=" in a and "HERE" not in a and True not in [b in a for b in M]: Ansli.add(a.replace(".", "").replace(" ", "").replace("?", "")) if "Exit:" in a and a.split(") ")[1].split( "(")[0] in Reasons and "=" not in a: ReasWHY.add(a.split(") ")[1]) if "Fail:" in a and a.split(") ")[1].split( "(")[0] in Reasons and "=" not in a: ReasWHEN.add(a.split(") ")[1]) if not bWhen and not bWhy and not bHowMany and not bWhat: return True if "true" in rs.replace(" ", "") else "No/ne" if bWhy: return re.sub( r'(\,|\s|\(|\))', ' ', " and ".join( r for r in ReasWHY if r.replace(" ", "") != ret.split("A")[1].replace(" ", "")) ) if bHow or "true" in rs.replace(" ", "") else "" if bWhen: return re.sub( r'(\,|\s|\(|\))', ' ', " and ".join( r for r in ReasWHEN if r.replace(" ", "") != ret.split("A")[1].replace(" ", "")) ) if "true" not in rs.replace(" ", "") else "" return Ansli if not bHowMany else len(Ansli)
def get_fortune(request): msg = "" while not msg: # Avoid empty messages that are returned sometimes ... msg = Popen([settings.FORTUNE_BIN, settings.FORTUNE_PATH], stdout=PIPE).communicate()[0] #FIXME: to be split and passed to template as context msg = '<div class="italic">' + msg msg = msg.replace("-- ", '</div><div class="author">') msg += '</div>' msg = msg.replace("\n","<br />") return HttpResponse(msg)
def rename_file (video_file_name_extn, extn): # Extract the meta data into a temporary file "meta.txt" Popen ('ffmpeg -i \"' + video_file_name_extn + '\" -f ffmetadata ' + ' meta.txt' , shell=True, stdout=PIPE).stdout.read() # Extract the show name show_name = Popen ('grep show= meta.txt' , shell=True, stdout=PIPE).stdout.read() # Do not rename if it is not a show if (show_name == ''): system ('rm -rf meta.txt') return (video_file_name_extn) show_name = show_name.replace ('show=', '') show_name = show_name.rstrip() # Extract the season number season = Popen ('grep season_number meta.txt' , shell=True, stdout=PIPE).stdout.read() season = season.replace ('season_number=', '') season = season.rstrip() # Extract the episode number episode_sort = Popen ('grep episode_sort meta.txt' , shell=True, stdout=PIPE).stdout.read() episode_sort = episode_sort.replace ('episode_sort=', '') episode_sort = episode_sort.rstrip() # Extract the episode title episode_name = Popen ('grep title= meta.txt' , shell=True, stdout=PIPE).stdout.read() episode_name = episode_name.replace ('title=', '') episode_name = episode_name.rstrip() # Delete temporary "meta.txt" file. system ('rm -rf meta.txt') # Construct the complete file name final_episode_name = '' if (int(season)<10): final_episode_name = final_episode_name + show_name + ' S0' + season else: final_episode_name = final_episode_name + show_name + ' S' + season if (int(episode_sort) < 10): final_episode_name = final_episode_name + 'E0' + episode_sort else: final_episode_name = final_episode_name + 'E' + episode_sort final_episode_name = final_episode_name + ' ' + episode_name + extn # Return the constructed file name return final_episode_name
def __init__(self, dist): try: if dist == 'Mac OSX': cpu = Popen(['sysctl', '-n', 'machdep.cpu.brand_string'], stdout=PIPE).communicate()[0].decode( 'Utf-8').split('\n')[0] c = cpu.replace('(R)', '').replace('(TM)', '').replace('CPU', '').split() cpuinfo = ' '.join(c) elif dist == 'FreeBSD': cpu = Popen( ['sysctl', '-n', 'hw'], stdout=PIPE).communicate()[0].decode('Utf-8').split('\n') cpuinfo = re.sub( ' +', ' ', cpu[1].replace('model name\t: ', '').rstrip('\n')) else: txt = open('/proc/cpuinfo').readlines() cpuinfo = '' for line in txt: if line.find('model name') >= 0: cpuinfo = line.split(': ')[1].strip('\n') except: cpuinfo = 'unknown' self.key = 'CPU' self.value = cpuinfo
def _convertToHTML(self): """ Convert the PDF text content to HTML with pdftohtml NOTE: XXX check that command exists and was executed successfully """ if not self.hasData(): return '' tmp = tempfile.NamedTemporaryFile() tmp.write(self.getData()) tmp.seek(0) command_result = None try: command = ['pdftohtml', '-enc', 'UTF-8', '-stdout', '-noframes', '-i', tmp.name] try: command_result = Popen(command, stdout=PIPE).communicate()[0] except OSError, e: if e.errno == errno.ENOENT: raise ConversionError('pdftohtml was not found') raise finally: tmp.close() # Quick hack to remove bg color - XXX h = command_result.replace('<BODY bgcolor="#A0A0A0"', '<BODY ') # Make links relative h = h.replace('href="%s.html' % tmp.name.split(os.sep)[-1], 'href="asEntireHTML') return h
def find_cal_mwats(obs_id): obs_id = obs_id.split('\n')[0] obs_id = obs_id.strip() date_output = Popen(["python", "/short/ek6/MWA_Code/bin/get_observation_info.py", "-g", str(obs_id)], stdout=PIPE).communicate()[0] date_output = date_output.split()[7] date_output = date_output.replace('/', '-') date_output = date_output[1:11] print "Observation date "+date_output os.chdir('/short/ek6/CALS/') cal_list = open('MWATS_cal_list.txt', 'r') return_cal = None for line in cal_list: sdate = line.split(',')[0] cal_id = line.split(',')[1] cal_id = cal_id.split(' ')[1] if sdate == date_output: print 'Recomended calibrator is '+cal_id for cal in glob.glob('*.cal'): cal_num = cal[0:10] if cal_id.split('\n')[0] == cal_num: print "Found calibration file "+cal return_cal = '/short/ek6/CALS/'+cal if return_cal == None: print "No calibrator file found, please generate it" return return_cal
def testUnoConverterOdtToDoc(self): """Test script unoconverter""" mimemapper = dict(filter_list=[('doc', 'com.sun.star.text.TextDocument', 'MS Word 97')], doc_type_list_by_extension=dict(doc=['com.sun.star.text.TextDocument'])) mimemapper_pickled = json.dumps(mimemapper) python = join(self.office_binary_path, "python") command = [exists(python) and python or "python", pkg_resources.resource_filename("cloudooo.handler.ooo", "/helper/unoconverter.py"), "--convert", "--uno_path=%s" % self.uno_path, "--office_binary_path=%s" % self.office_binary_path, "--hostname=%s" % self.hostname, "--port=%s" % self.port, "--document_url=%s" % self.document.getUrl(), "--destination_format=%s" % "doc", "--source_format=%s" % "odt", "--mimemapper=%s" % mimemapper_pickled] stdout, stderr = Popen(command, stdout=PIPE, stderr=PIPE).communicate() self.assertEquals(stderr, '') output_url = stdout.replace('\n', '') self.assertTrue(exists(output_url), stdout) mime = magic.Magic(mime=True) self.assertEquals(mime.from_file(output_url), 'application/msword') self.document.trash() self.assertEquals(exists(output_url), False)
def backup_database(request): if request.method == 'POST': output = Popen(['which', 'mysqldump'], stdout=PIPE, close_fds=True).communicate()[0] mysqldump_bin = output.replace('\n','') cmd = mysqldump_bin+' -h %s --opt --compact --skip-add-locks -u %s -p%s %s' % \ (getattr(settings.DATABASES['default'], 'HOST', 'localhost'), settings.DATABASES['default']['USER'], settings.DATABASES['default']['PASSWORD'], settings.DATABASES['default']['NAME']) pop1 = Popen(cmd.split(" "), stdout=PIPE, close_fds=True) pop2 = Popen(["bzip2", "-c"], stdin=pop1.stdout, stdout=PIPE, close_fds=True) output = pop2.communicate()[0] default_storage.save(BACKUP_DIR+"/"+datetime.today().strftime("%Y-%m-%d_%H:%M:%S")+"_db.sql.bz2", ContentFile(output)) files = default_storage.listdir(BACKUP_DIR)[1] files.sort(reverse=True) return render_to_response('diagnostic/backupdb.html', {'files':files,}, context_instance=RequestContext(request))
def help_test(self): p = Popen( "python tests/tools.py -h", stdout=PIPE).communicate()[0] self.assertEqual( p.replace("\r", "").strip(), expected_h)
def __launch_desktop_blocker(self, session_name, user_id, x11_display): print "Launch desktop-blocker to '%s'" % session_name from os import environ env = environ.copy() env["DISPLAY"] = x11_display proclist = gtop.proclist(gtop.PROCLIST_KERN_PROC_UID, int(user_id)) if len(proclist) > 0 : from subprocess import Popen, PIPE lang_var = Popen('cat /proc/%s/environ | tr "\\000" "\\n" | grep ^LANG= ' % proclist[0] , shell=True, stdout=PIPE).stdout.readline().strip("\n") if len(lang_var) > 0 : env["LANG"] = lang_var.replace("LANG=","") pid = Popen('nanny-desktop-blocker', env=env).pid else: pid = Popen('nanny-desktop-blocker', env=env).pid pid_file = "/var/lib/nanny/desktop_blocks_pids/%s.%s" % (user_id, os.path.basename(session_name)) fd = open(pid_file, "w") fd.write(str(pid)) fd.close() pid, ret = os.waitpid(pid, 0) if os.path.exists(pid_file) : os.unlink(pid_file) return session_name, user_id, ret
def get_status(table=None, worker=None, completed=False, qualified=False): global DB_PASSWORD if table == None or table == '': table = "assignment" where = "WHERE TRUE " if table == "assignment": if worker: where += "AND amt_worker_id='%s' "%worker if completed == "1": where += "AND NOT ISNULL(completed) " if completed == "0": where += "AND ISNULL(completed) " elif table == "worker": if qualified == "1": where += "AND NOT ISNULL(qualified) " if qualified == "0": where += "AND ISNULL(completed) " sql ="select * from %s %s;"%(table, where) cmd = ["mysql","-u","mdi","--password=%s"%DB_PASSWORD,"-H", "-e",sql, "mdi"] # Python 2.7 # out = subprocess.check_output(cmd) out = Popen(cmd, stdout=PIPE).communicate()[0] out = out.replace("BORDER=1","") return "<HTML><style>table {border:0 white; font-size:10pt; font-family:sans-serif;} tr:nth-child(odd) { background-color:#ddd; } tr:nth-child(even) { background-color:#fff; }</style><BODY>"+out + "</BODY></HTML>"
def __launch_desktop_blocker(self, session_name, user_id, x11_display): print "Launch desktop-blocker to '%s'" % session_name from os import environ env = environ.copy() env["DISPLAY"] = x11_display proclist = gtop.proclist(gtop.PROCLIST_KERN_PROC_UID, int(user_id)) if len(proclist) > 0: from subprocess import Popen, PIPE lang_var = Popen( 'cat /proc/%s/environ | tr "\\000" "\\n" | grep ^LANG= ' % proclist[0], shell=True, stdout=PIPE).stdout.readline().strip("\n") if len(lang_var) > 0: env["LANG"] = lang_var.replace("LANG=", "") pid = Popen('nanny-desktop-blocker', env=env).pid else: pid = Popen('nanny-desktop-blocker', env=env).pid pid_file = "/var/lib/nanny/desktop_blocks_pids/%s.%s" % ( user_id, os.path.basename(session_name)) fd = open(pid_file, "w") fd.write(str(pid)) fd.close() pid, ret = os.waitpid(pid, 0) if os.path.exists(pid_file): os.unlink(pid_file) return session_name, user_id, ret
def calcularGrosor(self, filename): # ../lsd_1.6/lsd -P salida.eps imagenes/Pelo40X.pgm salida.txt # output = Popen(["../lsd_1.6/lsd", "-T", self.minimo.get(), "-t", self.limite.get(), "-a", "100", "-P", "salida.eps", filename, "salida.txt"], stdout=PIPE).communicate()[0] output = Popen([ "../lsd_1.6/lsd", "-T", self.minimo.get(), "-t", self.limite.get(), "-P", "salida.eps", filename, "salida.txt" ], stdout=PIPE).communicate()[0] output2 = Popen(["./backup-de-la-foto.sh"], ).communicate()[0] output = output.replace('Grosor del PELO en pixels : ', '') self.grosor.delete(0, END) self.grosor.insert(0, output) self.grosormicron.delete(0, END) self.grosormicron.insert(0, float(output) * float(self.micron.get())) print output self.lbl_estadistica.delete('1.0', END) # Las mediciones por rangos output = Popen(["./procesar_rangos.sh", filename], stdout=PIPE).communicate()[0] self.lbl_estadistica.insert('1.0', output) # Las mediciones clasicas output = Popen( ["./procesar.sh", self.minimo.get(), self.limite.get(), filename], stdout=PIPE).communicate()[0] self.lbl_estadistica.insert('4.0', '\n') self.lbl_estadistica.insert('5.0', output)
def version_test(self): p = Popen( "python tests/tools.py --version", stdout=PIPE).communicate()[0] self.assertEqual( p.replace("\r", "").strip(), "0.0.1")
def backup_database(request): if request.method == 'POST': output = Popen(['which', 'mysqldump'], stdout=PIPE, close_fds=True).communicate()[0] mysqldump_bin = output.replace('\n', '') cmd = mysqldump_bin+' -h %s --opt --compact --skip-add-locks -u %s -p%s %s' % \ (getattr(settings.DATABASES['default'], 'HOST', 'localhost'), settings.DATABASES['default']['USER'], settings.DATABASES['default']['PASSWORD'], settings.DATABASES['default']['NAME']) pop1 = Popen(cmd.split(" "), stdout=PIPE, close_fds=True) pop2 = Popen(["bzip2", "-c"], stdin=pop1.stdout, stdout=PIPE, close_fds=True) output = pop2.communicate()[0] default_storage.save( BACKUP_DIR + "/" + datetime.today().strftime("%Y-%m-%d_%H:%M:%S") + "_db.sql.bz2", ContentFile(output)) files = default_storage.listdir(BACKUP_DIR)[1] files.sort(reverse=True) return render_to_response('diagnostic/backupdb.html', { 'files': files, }, context_instance=RequestContext(request))
def _convertToHTML(self): """Convert the PDF text content to HTML with pdftohtml """ if not self.hasData(): return '' tmp = tempfile.NamedTemporaryFile() tmp.write(self.getData()) tmp.seek(0) command_result = None try: command = [ 'pdftohtml', '-enc', 'UTF-8', '-stdout', '-noframes', '-i', tmp.name ] try: command_result = Popen(command, stdout=PIPE).communicate()[0] except OSError, e: if e.errno == errno.ENOENT: raise ConversionError('pdftohtml was not found') raise finally: tmp.close() # Quick hack to remove bg color - XXX h = command_result.replace('<BODY bgcolor="#A0A0A0"', '<BODY ') # Make links relative h = h.replace('href="%s.html' % tmp.name.split(os.sep)[-1], 'href="asEntireHTML') return h
def test_version_num(self): current_branch = Popen( ['git', 'branch', '--show-current'], stdout=PIPE).communicate()[0].decode("utf-8").strip() if not current_branch: current_branch = p_HEAD_REF.read_text() self.assertRegex( current_branch, r"release/\d+\.\d+\.\d+", "Release tests must be run on a release branch on the form 'release/x.y.z'." ) version_number = current_branch.replace("release/", "") self.assertRegex( version_number, r'\d+\.\d+\.(?!99)\d+', "Releases cannot have the x.y.99 development bugfix release number." ) self.assertEqual( version_number, p_VERSION.read_text(), f"{p_VERSION} has not been updated to the correct version number.") self.assertEqual( p_RELEASE_NOTES.read_text().splitlines()[0], r"# zcbor v. " + version_number, f"{p_RELEASE_NOTES} has not been updated with the correct version number." ) tags_stdout, _ = Popen(['git', 'tag'], stdout=PIPE).communicate() tags = tags_stdout.decode("utf-8").strip().splitlines() self.assertNotIn( version_number, tags, "Version number already exists as a tag. Has the version number been updated?" )
def getSystemID(): sccCredentialsFile = '/etc/zypp/credentials.d/SCCcredentials' nccCredentialsFile = '/etc/zypp/credentials.d/NCCcredentials' nccCredentialsFileRH = '/etc/NCCcredentials' zmdDeviceFile = '/etc/zmd/deviceid' zmdSecretFile = '/etc/zmd/secret' if os.path.exists(sccCredentialsFile): return parseSystemID(sccCredentialsFile) elif os.path.exists(nccCredentialsFile): return parseSystemID(nccCredentialsFile) elif os.path.exists(nccCredentialsFileRH): return parseSystemID(nccCredentialsFileRH) elif os.path.exists(zmdDeviceFile) and os.path.exists(zmdSecretFile): f = open(zmdDeviceFile, 'r') guid = f.readline() guid = guid.strip() f.close() f = open(zmdSecretFile, 'r') secret = f.readline() secret = secret.strip() f.close() elif uuid is None: guid = Popen(['uuidgen'], stdout=PIPE).communicate()[0] guid = guid.replace('-', '').strip() time.sleep(1) secret = Popen(['uuidgen'], stdout=PIPE).communicate()[0] secret = guid.replace('-', '').strip() else: guid = str(uuid.uuid4()) guid = guid.replace('-', '').strip() time.sleep(1) secret = str(uuid.uuid4()) secret = secret.replace('-', '').strip() if os.path.exists('/etc/zypp/'): if not os.path.exists('/etc/zypp/credentials.d'): os.makedirs('/etc/zypp/credentials.d') f = open(nccCredentialsFile, 'w') else: f = open(nccCredentialsFileRH, 'w') f.write("username=%s\npassword=%s\n" % (guid, secret)) f.close() return {'guid': guid, 'secret': secret}
def bp_test_debug(self): p = Popen( "python tests/tools.py bp-model thing1.db thing2.txt --flag=True --debug", stdout=PIPE).communicate()[0] self.assertEqual( p.replace("\r", "").strip(), expected_debug )
def import_key(tempdir,kfile): "Imports a key to the keyring in tempdir and returns the keyid" import re out = Popen([GPG,'--homedir',tempdir,'--import',kfile],stderr=PIPE).communicate()[1].decode('utf-8') m = re.search("gpg: key ([0-9A-F]+).*imported",out.replace("\n"," ")) if m: return m.group(1) raise RuntimeError("No PGP key imported")
def get_actual_ip(self, service): """get actual ip by external service Args: service: curl or dig Returns: actual ip ToDo: nothing """ if (service == "dig"): act_ip = Popen([ "dig", "+short", "myip.opendns.com", "@resolver1.opendns.com" ], stdout=PIPE).communicate()[0] else: act_ip = Popen(["curl", "ifconfig.co"], stdout=PIPE).communicate()[0] #act_ip = Popen(["curl", "curlmyip.com"], stdout=PIPE).communicate()[0] #clean up the result act_ip = act_ip.replace('\n', '').replace('\r', '') #check ip chkip_res = self.check_ip(act_ip) #do another try if it failed if (chkip_res): if (service == "dig"): act_ip = Popen([ "dig", "+short", "myip.opendns.com", "@resolver1.opendns.com" ], stdout=PIPE).communicate()[0] else: act_ip = Popen(["curl", "ifconfig.co"], stdout=PIPE).communicate()[0] #clean up the result act_ip = act_ip.replace('\n', '').replace('\r', '') return act_ip
def bp_test_kw(self): p = Popen( "python tests/tools.py bp-model thing1.db thing2.txt --flag=True", stdout=PIPE).communicate()[0] self.assertEqual( p.replace("\r", "").strip(), ("('thing1.db', 'thing2.txt', 'A', True)\n" "Analyzing...") )
def get_service_status(servicename): try: service_data = Popen(["service", servicename, "status"], stdout=PIPE) service_data = check_output(["grep", "Active"], stdin=service_data.stdout).decode("utf-8") service_data = service_data.replace("\n", '') except CalledProcessError: service_data = 'Service not found' return service_data
def pianobar_status(self, i3s_output_list, i3s_config): title, title_err = Popen(['bash', 'bin/get_song_title'], stdout=PIPE, stderr=PIPE).communicate() time, time_err = Popen(['bash', 'bin/get_song_time'], stdout=PIPE, stderr=PIPE).communicate() title = title.split('\n', 1)[0].split('>', 1)[1].split('" on "', 1)[0].strip() + '"' time = time.replace('\n', '') return { 'full_text': time + ' | ' + title, 'cached_until': 0 }
def check_node_version(): try: actual = Popen([NODE_JS, '--version'], stdout=PIPE).communicate()[0].strip() version = tuple(map(int, actual.replace('v', '').split('.'))) if version >= EXPECTED_NODE_VERSION: return True print >> sys.stderr, 'warning: node version appears too old (seeing "%s", expected "%s")' % (actual, 'v' + ('.'.join(map(str, EXPECTED_NODE_VERSION)))) return False except Exception, e: print >> sys.stderr, 'warning: cannot check node version:', e return False
def promo_count(): sql = 'select count(*) from rpsods.pcp_promotion;' mysql_path = get_mysql_path() sql_file = open('query.sql', 'w') sql_file.write(sql) sql_file.close() path = os.getcwd() mysql_exe = '\"' + mysql_path[0] + '\\bin\\mysql.exe' + '\"' result = Popen(mysql_exe + ' -u' + config.mysql_user + ' -p' + config.mysql_pass + ' rpsods < "' + path + '\\query.sql"', shell=True, stdout=PIPE).communicate() os.remove('query.sql') result = result[0].decode() return str(result.replace("count(*)\r\n", "").replace("/r/n", ""))
def bp_help_test(self): p = Popen( "python tests/tools.py bp-model --docstring", stdout=PIPE).communicate()[0] self.assertEqual( p.replace("\r", "").strip(), ("Docstring for bp_model:\nBuilding Permit Model.\n" " Args:\n" " db_in (str): File path to SQLite database\n" " file_out (str): File path to ...\n" " name_opt (str): A string\n" " flag (bool): a flag (default False)") )
def env(node, path): output = Popen(["hconfig"], stdin=PIPE, stdout=PIPE, stderr=STDOUT, shell=True) output = output.stdout.read() lst = output.replace("'", "").split("\n") lst = [j for i in lst for j in i.split(" := ")] lst = dict(zip(lst[::2], lst[1::2])) data = json.dumps(lst, sort_keys=True, indent=4, separators=(',', ': ')) with open(path, 'w') as f: f.write(data)
def check_exec(executable): """ Check if the executable exist :rtype : path :param executable: :return: """ output, error = Popen(['which', executable], stdout=PIPE, stderr=PIPE).communicate() if error: logging.info('%s Not found' % executable) return "" logging.info('Path to %s : %s' % (executable, output.replace("\n", ""))) return output
def check_source_md5(self, filename): if self.is_installed: sourcedir= Popen(["rpm", "-E", '%_sourcedir' ], stdout=subprocess.PIPE).stdout.read()[:-1] # replace %{name} by the specname package_name = Popen(["rpm", "-qp", self.filename, '--qf', '%{name}' ], stdout=subprocess.PIPE).stdout.read() sourcedir = sourcedir.replace("%{name}", package_name) sourcedir = sourcedir.replace("%name", package_name) src_files = glob.glob( sourcedir + '/*') # src_files = glob.glob(os.path.expanduser('~/rpmbuild/SOURCES/*')) if src_files: for name in src_files: if filename and os.path.basename(filename) != os.path.basename(name): continue self.log.debug("Checking md5 for %s" % name) sum,file = self._md5sum(name) return sum else: print('no sources found in install SRPM') return "ERROR" else: print "SRPM is not installed" return "ERROR"
def restart(): from subprocess import Popen, PIPE from six.moves.urllib.parse import urlparse urlparts = urlparse(request.url) if urlparts.netloc == "beta.lmfdb.org": command = ['bash', '/home/lmfdb/restart-dev'] elif urlparts.netloc in ["prodweb1.lmfdb.xyz", "prodweb2.lmfdb.xyz"]: command = ['bash', '/home/lmfdb/restart-web'] else: command = None if command: out = Popen(command, stdout=PIPE).communicate()[0] return out.replace('\n', '<br>') else: return "Only supported in beta.lmfdb.org, prodweb1.lmfdb.xyz, and prodweb2.lmfdb.xyz"
def AcquireResult(allowed_delay_min=5): """using SSH, returns 1 / 0 / None if iphone is around (not directly pinging > only reading last logs) if more time passed than allowed_delay_min since last ping > returns None *too old log ** to be run from another device with SSH / RSA keys on it""" com = "tail -1 " + os.path.join(Dirs()['LOG'], 'log_ping_iPhone.txt') stdout, stderr = Popen(com.split(' '), stdout=PIPE, stderr=PIPE).communicate() if type(stdout) != str: stdout = stdout.decode( "utf-8") #for python3 > return is Byte like object #return LAST False / True return stdout.replace('\n', '').split('\t')[-1] != 'False'
def mediainfo(filepath): """Return dictionary with media info(codec, duration, size, bitrate...) from filepath """ from .audio_segment import AudioSegment prober = get_prober_name() command_args = [ "-v", "quiet", "-show_format", "-show_streams", filepath ] command = [prober, '-of', 'old'] + command_args res = Popen(command, stdout=PIPE) output = res.communicate()[0].decode("utf-8") if res.returncode != 0: command = [prober] + command_args output = Popen(command, stdout=PIPE).communicate()[0].decode("utf-8") rgx = re.compile(r"(?:(?P<inner_dict>.*?):)?(?P<key>.*?)\=(?P<value>.*?)$") info = {} if sys.platform == 'win32': output = output.replace("\r", "") for line in output.split("\n"): # print(line) mobj = rgx.match(line) if mobj: # print(mobj.groups()) inner_dict, key, value = mobj.groups() if inner_dict: try: info[inner_dict] except KeyError: info[inner_dict] = {} info[inner_dict][key] = value else: info[key] = value return info
def run_simple_grading(stations=['1','2','3','4','5','6']): """ Run simple_grading.sh over the list of given station numbers. See command line option documentation for parameter documentation. """ station_objects = [] for num in stations: station_json = Popen(["./simple_grading.sh", os.path.join(STATION_PATH, "station_" + num)], stdout=PIPE).communicate()[0] station_json = station_json.replace('\n','') stats = json.loads(station_json) stats['Station'] = num station_objects.append(stats) return station_objects
def __init__(self,dist): #file = open('/proc/cpuinfo').readlines() try: if dist == 'Mac OSX': cpu = Popen(['sysctl', '-n','machdep.cpu.brand_string'], stdout=PIPE).communicate()[0].decode('Utf-8').split('\n')[0] c = cpu.replace('(R)','').replace('(TM)','').replace('CPU','').split() cpuinfo = ' '.join(c) elif dist == 'FreeBSD': file = Popen(['sysctl', '-n','hw'], stdout=PIPE).communicate()[0].decode('Utf-8').split('\n') cpuinfo = re.sub(' +', ' ', file[1].replace('model name\t: ', '').rstrip('\n')) else: file = Popen(['grep', '-i', 'model name\t: ', '/proc/cpuinfo'], stdout=PIPE).communicate()[0].decode('Utf-8').split('\n') cpuinfo = re.sub(' +', ' ', file[0].replace('model name\t: ', '')) except: cpuinfo = 'unknown' self.key = 'CPU' self.value = cpuinfo
def main(): parser = argparse.ArgumentParser() parser.add_argument('-c', dest='collector', help='Zenoss collector.', required=True) args = parser.parse_args() collector = args.collector username = "******" password = secrets.f5_certificate_check[username]['password'] z = ZenossAPI() big_ip_devices = z.get_devices('/zport/dmd/Devices/Network/BIG-IP') collector_devices = [] if big_ip_devices['result'].get('devices', False): for device in big_ip_devices['result']['devices']: if device['collector'] == collector: collector_devices.append(device) else: print 'No BIG-IP devices found on {}\n{}'.format(collector, big_ip_devices) for device in collector_devices: command = "/opt/zenoss/scripts/get_f5_details.py {} {} '{}'".format(device['ipAddressString'], username, password) stdout, stderr = Popen(command, stdout=PIPE, stderr=PIPE, shell=True).communicate() if not stderr: correct_device_class = '/Devices' + stdout.replace('\n', '') zenoss_device = z.get_device(name=device['name']) current_device_class = zenoss_device['deviceClass'] if current_device_class.split('/')[-1].isdigit(): current_device_class = current_device_class.replace('/{}'.format(current_device_class.split('/')[-1]), '') if 'Cannot determine the class' in correct_device_class: print '{} for {}.'.format(correct_device_class, device['name']) else: print 'Class of {}: {}. Correct class: {}.'.format(device['name'], current_device_class, correct_device_class) if current_device_class == correct_device_class: print '\t\t\tOK' else: print '\t\t\tNOT_OK' file_name = '/tmp/f5_add_{}'.format(device['name']) f = open(file_name, 'w') f.write('{};{};{};{};{}'.format(device['name'], device['ipAddressString'], username, password, zenoss_device['snmpCommunity'])) f.close() add_command = "/opt/zenoss/scripts/add_f5_device.py --file {} -u monapps -p '***' -d".format(file_name) stdout, stderr = Popen(add_command, stdout=PIPE, stderr=PIPE, shell=True).communicate() print stdout print stderr else: print 'Cannot get details for {}'.format(device['name'])
def check_version_and_upload(dir_path): os.chdir(dir_path) try: shutil.rmtree(os.path.join(dir_path, 'build')) except OSError: pass except Exception as e: print(e) try: shutil.rmtree(os.path.join(dir_path, 'dist')) except OSError: pass except Exception as e: print(e) version = Popen(["python", 'setup.py', '--version'], stdout=PIPE).stdout.read() version = version.strip().decode() package_name = Popen(["python", 'setup.py', '--name'], stdout=PIPE).stdout.read() package_name = package_name.strip().decode().replace(' ', '-') package_name = package_name.replace('---', '-').lower() remote_version = pypi.package_releases(package_name) print("{:<65} {:<10} {:<10}".format(package_name, version, remote_version[0])) updated = False if len(remote_version) == 0 or version_compare(version, remote_version[0]) < 0: print('----- UPLOADING PYPI -----', package_name) if os.path.isdir('./dist'): shutil.rmtree('./dist') Popen(['python', 'setup.py', 'sdist', 'bdist_wheel'], stdout=PIPE).communicate() Popen(['twine', 'upload', os.path.join('dist', '*')]).communicate() updated = True os.chdir(CURRENT_DIRECTORY) return updated, package_name, version
def export_database(request): output = Popen(['which', 'mysqldump'], stdout=PIPE, close_fds=True).communicate()[0] mysqldump_bin = output.replace('\n','') cmd = mysqldump_bin+' -h %s --opt --compact --skip-add-locks -u %s -p%s %s' % \ (getattr(settings.DATABASES['default'], 'HOST', 'localhost'), settings.DATABASES['default']['USER'], settings.DATABASES['default']['PASSWORD'], settings.DATABASES['default']['NAME']) pop1 = Popen(cmd.split(" "), stdout=PIPE, close_fds=True) pop2 = Popen(["bzip2", "-c"], stdin=pop1.stdout, stdout=PIPE, close_fds=True) output = pop2.communicate()[0] response = HttpResponse(output, mimetype="application/octet-stream") response['Content-Disposition'] = 'attachment; filename=%s' % date.today().__str__()+'_db.sql.bz2' return response
def get_project_package(project_root, project_import): """ Get the project package from either the import passed in or the project root using go list :type project_root: string :param project_root: The location of the project root :type project_import: string :param project_import: The import path for the project root :rtype: string :return: The project package import path """ if not project_import: project_import, _ = Popen(["go", "list"], stdout=PIPE, cwd=project_root).communicate() return project_import.replace("'", "")
def launch(command, hooks_file): from subprocess import Popen, PIPE import sys, os PYJACKER_SOURCE = "hijacker.c" PYJACKER_LIB = "libhijacker.so" try: with open("hijacker.c", "w") as f: f.write(generator.generate()) except IOError as e: print('[-] Error generating c source: %s' % e) sys.exit(-1) print('[+] Generated c source for hijacking library') compile_cmd = ['gcc', PYJACKER_SOURCE, '-o', PYJACKER_LIB, '-shared', '-fPIC', '-Wall', '-O2'] try: output = Popen(['python-config', '--cflags', '--libs'], stdout=PIPE).communicate()[0] compile_cmd.extend([arg.strip() for arg in output.replace('\n', ' ').split()]) except OSError as e: print('[-] Error getting compile flags: %s' % e) sys.exit(-1) print('[+] Got compile flags') gcc = Popen(compile_cmd) if gcc.wait() != 0: print('[-] Error compiling library') sys.exit(-1) print('[+] Compiled library in %s' % PYJACKER_LIB) print('[+] Launcing program\n') env = os.environ env['LD_PRELOAD'] = os.path.abspath(PYJACKER_LIB) env['PYJACKER_HOOKS'] = os.path.splitext(os.path.basename(hooks_file))[0] env['PYTHONPATH'] = os.path.dirname(os.path.abspath(hooks_file)) ret = 0 try: program = Popen(command, env=env) ret = program.wait() finally: os.remove(PYJACKER_SOURCE) os.remove(PYJACKER_LIB) return ret
def check_version_and_upload(dir_path): os.chdir(dir_path) try: shutil.rmtree(os.path.join(dir_path, 'build')) except OSError: pass except Exception as e: print(e) try: shutil.rmtree(os.path.join(dir_path, 'dist')) except OSError: pass except Exception as e: print(e) version = Popen(["python", 'setup.py', '--version'], stdout=PIPE).stdout.read() version = version.strip().decode() package_name = Popen(["python", 'setup.py', '--name'], stdout=PIPE).stdout.read() package_name = package_name.strip().decode().replace(' ', '-') package_name = package_name.replace('---', '-').lower() remote_version = pypi.package_releases(package_name) print( "{:<65} {:<10} {:<10}".format(package_name, version, remote_version[0]) ) updated = False if len(remote_version) == 0 or version_compare(version, remote_version[0]) < 0: print('----- UPLOADING PYPI -----', package_name) if os.path.isdir('./dist'): shutil.rmtree('./dist') Popen(['python', 'setup.py', 'sdist', 'bdist_wheel'], stdout=PIPE).communicate() Popen(['twine', 'upload', os.path.join('dist','*')]).communicate() updated = True os.chdir(CURRENT_DIRECTORY) return updated, package_name, version
def calcularGrosor(self,filename): # ../lsd_1.6/lsd -P salida.eps imagenes/Pelo40X.pgm salida.txt # output = Popen(["../lsd_1.6/lsd", "-T", self.minimo.get(), "-t", self.limite.get(), "-a", "100", "-P", "salida.eps", filename, "salida.txt"], stdout=PIPE).communicate()[0] output = Popen(["../lsd_1.6/lsd", "-T", self.minimo.get(), "-t", self.limite.get(), "-P", "salida.eps", filename, "salida.txt"], stdout=PIPE).communicate()[0] output2 = Popen(["./backup-de-la-foto.sh"], ).communicate()[0] output = output.replace('Grosor del PELO en pixels : ', '') self.grosor.delete(0, END) self.grosor.insert(0, output) self.grosormicron.delete(0, END) self.grosormicron.insert(0, float(output)*float(self.micron.get())) print output self.lbl_estadistica.delete('1.0', END) # Las mediciones por rangos output = Popen(["./procesar_rangos.sh", filename ], stdout=PIPE).communicate()[0] self.lbl_estadistica.insert('1.0', output) # Las mediciones clasicas output = Popen(["./procesar.sh", self.minimo.get(), self.limite.get(), filename ], stdout=PIPE).communicate()[0] self.lbl_estadistica.insert('4.0', '\n') self.lbl_estadistica.insert('5.0', output)
def get_project_package(project_root, project_import): """ Get the project package from either the import passed in or the project root using go list :type project_root: string :param project_root: The location of the project root :type project_import: string :param project_import: The import path for the project root :rtype: string :return: The project package import path """ if not project_import: project_import, _ = Popen( ["go", "list"], stdout=PIPE, cwd=project_root ).communicate() return project_import.replace("'", "")
def possibleToolLocations(): homebin = '%s/bin/plotdevice'%os.environ['HOME'] localbin = '/usr/local/bin/plotdevice' locations = [homebin, localbin] # find the user's login shell out, _ = Popen(['dscl','.','-read','/Users/'+os.environ['USER'],'UserShell'], stdout=PIPE).communicate() shell = out.replace('UserShell:','').strip() # try launching a shell to extract the user's path if shell: out, _ = Popen([shell,"-l"], stdout=PIPE, stderr=PIPE, stdin=PIPE).communicate("echo $PATH") for path in out.strip().split(':'): path += '/plotdevice' if '/sbin' in path: continue if path.startswith('/bin'): continue if path.startswith('/usr/bin'): continue if path in locations: continue locations.append(path) return locations
def find_app(resp=None): '''Returns a tupla of two items: the first is the string that's printable to the user; The second is the actual app name''' print "Please click on the window of which you want to find the app name." if resp != None: output = resp else: output = Popen(('xprop', 'WM_CLASS'), stdout=PIPE, stderr=STDOUT).communicate()[0] if 'xprop' in output: print 'find_app not working! Error message: ' + output sys.exit(1) output = output.split() output = output[3].lower() output = output.replace('"', '') msg = "The app's name is " + output + "." return (msg, output)
def _testOpenOffice(self, host, port): """Test if OpenOffice was started correctly""" logger.debug("Test OpenOffice %s - Pid %s" % (self.getAddress()[-1], self.pid())) python = join(self.office_binary_path, "python") args = [exists(python) and python or "python", pkg_resources.resource_filename("cloudooo", join('handler', 'ooo', "helper", "openoffice_tester.py")), "--hostname=%s" % host, "--port=%s" % port, "--uno_path=%s" % self.uno_path] logger.debug("Testing Openoffice Instance %s" % port) stdout, stderr = Popen(args, stdout=PIPE, stderr=PIPE, close_fds=True).communicate() stdout_bool = convertStringToBool(stdout.replace("\n", "")) if stdout_bool and stderr != "": logger.debug("%s\n%s" % (stderr, stdout)) return False else: logger.debug("Instance %s works" % port) return True
def possibleToolLocations(): homebin = "%s/bin/plotdevice" % os.environ["HOME"] localbin = "/usr/local/bin/plotdevice" locations = [homebin, localbin] # find the user's login shell out, _ = Popen(["dscl", ".", "-read", "/Users/" + os.environ["USER"], "UserShell"], stdout=PIPE).communicate() shell = out.replace("UserShell:", "").strip() # try launching a shell to extract the user's path if shell: out, _ = Popen([shell, "-l"], stdout=PIPE, stderr=PIPE, stdin=PIPE).communicate("echo $PATH") for path in out.strip().split(":"): path += "/plotdevice" if "/sbin" in path: continue if path.startswith("/bin"): continue if path.startswith("/usr/bin"): continue if path in locations: continue locations.append(path) return locations
def show_settings(): """ Shows settings of all of the major components. """ py_str = '%d.%d.%d' % sys.version_info[:3] try: from gi.repository import Gtk try: gtkver_str = '%d.%d.%d' % (Gtk.get_major_version(), Gtk.get_minor_version(), Gtk.get_micro_version()) except : # any failure to 'get' the version gtkver_str = 'unknown version' except ImportError: gtkver_str = 'not found' # no DISPLAY is a RuntimeError in an older pygtk (e.g. 2.17 in Fedora 14) except RuntimeError: gtkver_str = 'DISPLAY not set' #exept TypeError: To handle back formatting on version split try: from gi.repository import GObject try: pygobjectver_str = '%d.%d.%d' % GObject.pygobject_version except :# any failure to 'get' the version pygobjectver_str = 'unknown version' except ImportError: pygobjectver_str = 'not found' try: from gi.repository import Pango try: pangover_str = Pango.version_string() except :# any failure to 'get' the version pangover_str = 'unknown version' except ImportError: pangover_str = 'not found' try: import cairo try: pycairover_str = '%d.%d.%d' % cairo.version_info cairover_str = cairo.cairo_version_string() except :# any failure to 'get' the version pycairover_str = 'unknown version' cairover_str = 'unknown version' except ImportError: pycairover_str = 'not found' cairover_str = 'not found' try: from gi import Repository repository = Repository.get_default() if repository.enumerate_versions("OsmGpsMap"): from gi.repository import OsmGpsMap as osmgpsmap try: osmgpsmap_str = osmgpsmap._version except :# any failure to 'get' the version osmgpsmap_str = 'unknown version' else: osmgpsmap_str = 'not found' except ImportError: osmgpsmap_str = 'not found' try: from gi import Repository repository = Repository.get_default() if repository.enumerate_versions("GExiv2"): from gi.repository import GExiv2 try: gexiv2_str = GExiv2._version except: # any failure to 'get' the version gexiv2_str = 'unknown version' else: gexiv2_str = 'not found' except ImportError: gexiv2_str = 'not found' try: import PyICU try: pyicu_str = PyICU.VERSION icu_str = PyICU.ICU_VERSION except: # any failure to 'get' the version pyicu_str = 'unknown version' icu_str = 'unknown version' except ImportError: pyicu_str = 'not found' icu_str = 'not found' try: import bsddb3 as bsddb bsddb_str = bsddb.__version__ bsddb_db_str = str(bsddb.db.version()).replace(', ', '.')\ .replace('(', '').replace(')', '') except: bsddb_str = 'not found' bsddb_db_str = 'not found' try: from .gen.const import VERSION gramps_str = VERSION except: gramps_str = 'not found' if hasattr(os, "uname"): kernel = os.uname()[2] else: kernel = None lang_str = get_env_var('LANG','not set') language_str = get_env_var('LANGUAGE','not set') grampsi18n_str = get_env_var('GRAMPSI18N','not set') grampshome_str = get_env_var('GRAMPSHOME','not set') grampsdir_str = get_env_var('GRAMPSDIR','not set') try: dotversion_str = Popen(['dot', '-V'], stderr=PIPE).communicate(input=None)[1] if isinstance(dotversion_str, bytes) and sys.stdin.encoding: dotversion_str = dotversion_str.decode(sys.stdin.encoding) if dotversion_str: dotversion_str = dotversion_str.replace('\n','')[23:27] except: dotversion_str = 'Graphviz not in system PATH' try: if win(): gsversion_str = Popen(['gswin32c', '--version'], stdout=PIPE).communicate(input=None)[0] else: gsversion_str = Popen(['gs', '--version'], stdout=PIPE).communicate(input=None)[0] if isinstance(gsversion_str, bytes) and sys.stdin.encoding: gsversion_str = gsversion_str.decode(sys.stdin.encoding) if gsversion_str: gsversion_str = gsversion_str.replace('\n', '') except: gsversion_str = 'Ghostscript not in system PATH' os_path = get_env_var('PATH','not set') os_path = os_path.split(os.pathsep) print ("Gramps Settings:") print ("----------------") print (' python : %s' % py_str) print (' gramps : %s' % gramps_str) print (' gtk++ : %s' % gtkver_str) print (' pygobject : %s' % pygobjectver_str) print (' pango : %s' % pangover_str) print (' bsddb : %s' % bsddb_str) print (' bsddb.db : %s' % bsddb_db_str) print (' cairo : %s' % cairover_str) print (' pycairo : %s' % pycairover_str) print (' osmgpsmap : %s' % osmgpsmap_str) print (' GExiv2 : %s' % gexiv2_str) print (' ICU : %s' % icu_str) print (' PyICU : %s' % pyicu_str) print (' o.s. : %s' % sys.platform) if kernel: print (' kernel : %s' % kernel) print ('') print ("Environment settings:") print ("---------------------") print (' LANG : %s' % lang_str) print (' LANGUAGE : %s' % language_str) print (' GRAMPSI18N: %s' % grampsi18n_str) print (' GRAMPSHOME: %s' % grampshome_str) print (' GRAMPSDIR : %s' % grampsdir_str) print (' PYTHONPATH:') for folder in sys.path: print (" ", folder) print ('') print ("Non-python dependencies:") print ("------------------------") print (' Graphviz : %s' % dotversion_str) print (' Ghostscr. : %s' % gsversion_str) print ('') print ("System PATH env variable:") print ("-------------------------") for folder in os_path: print (" ", folder) print ('')
def get_hg(): hg_rev, error = Popen('hg id -b -n', stdout=PIPE, stderr=PIPE, shell=True).communicate() if error: errorlog('error@115', error) return None hg_rev, hg_branch = hg_rev.strip().split(" ") debuglog('branch', hg_branch) hg_rev = hg_rev.replace('+', '←').strip('←') try: hg_rev = int(hg_rev) if hg_rev < 0: return None hg_rev = str(hg_rev) except: pass hg_counts_cmd = 'hg status | grep -v \'.orig\'| awk \'{arr[$1]+=1} END {for (i in arr) {print i,arr[i]}}\'' hg_counts = { 'S': 0, #staged, 'X': 0, #conflicts, 'M': 0, #changed, '?': 0, #untracked, 'C': 1 #clean } if hg_rev.find('←') >= 0: hg_counts['X'] = int(Popen('hg resolve --list | wc -l', stdout=PIPE, shell=True).communicate()[0].strip()) for line in Popen(hg_counts_cmd, stdout=PIPE, shell=True).communicate()[0].strip().split("\n"): if line == '': continue hgst, count = line.split() hgst = hgst.replace('!', '?') hgst = hgst.replace('A', 'S') hgst = hgst.replace('R', 'S') hg_counts[hgst] += int(count) hg_counts['C'] = 0 if (hg_counts['X']) > 0: hg_counts['M'] -= hg_counts['X'] ahead, error = Popen('hg phase -r 0::tip | grep "draft" | wc -l', stdout=PIPE, stderr=PIPE, shell=True).communicate() if error: errorlog('error@151', error) ahead = 0 else: ahead = int(ahead) cmdline = 'hg log -r \'%s::branch("%s")\' -b \'%s\' | grep changeset | wc -l' % (hg_rev, hg_branch, hg_branch) debuglog('hg behind cmdline', cmdline) behind, error = Popen(cmdline, stdout=PIPE, stderr=PIPE, shell=True).communicate() if error: errorlog('error@156', error) behind = 0 else: behind = int(behind) - 1 remote = '' if behind: remote += '%s%s' % (symbols['behind'], behind) if ahead: remote += '%s%s' % (symbols['ahead of'], ahead) if remote == "": remote = '.' out = [ 'hg', '%s:%s' % (hg_branch, hg_rev), remote, str(hg_counts['S']), #staged, str(hg_counts['X']), #conflicts, str(hg_counts['M']), #changed, str(hg_counts['?']), #untracked, str(hg_counts['C']) #clean ] return out
def get(self): out, err = Popen('ls -r -1| grep test.*html| tail -20', shell=True, stdout=PIPE).communicate() self.write({'response_log': db.response_log.count() if db else -1, 'http_diff': db.http_diff.count() if db else -1, 'reports': out.replace("\n","<br>")})