def _get_soname(f):
# assuming GNU binutils / ELF
if not f:
return None
cmd = 'if ! type objdump >/dev/null 2>&1; then exit 10; fi;' \
"objdump -p -j .dynamic 2>/dev/null " + f
f = os.popen(cmd)
dump = f.read()
rv = f.close()
if rv == 10:
raise OSError, 'objdump command not found'
f = os.popen(cmd)
try:
data = f.read()
finally:
f.close()
res = re.search(r'\sSONAME\s+([^\s]+)', data)
if not res:
return None
return res.group(1)
python类popen()的实例源码
def _findLib_crle(name, is64):
if not os.path.exists('/usr/bin/crle'):
return None
if is64:
cmd = 'env LC_ALL=C /usr/bin/crle -64 2>/dev/null'
else:
cmd = 'env LC_ALL=C /usr/bin/crle 2>/dev/null'
for line in os.popen(cmd).readlines():
line = line.strip()
if line.startswith('Default Library Path (ELF):'):
paths = line.split()[4]
if not paths:
return None
for dir in paths.split(":"):
libfile = os.path.join(dir, "lib%s.so" % name)
if os.path.exists(libfile):
return libfile
return None
def iTunes_backup_looker():
backupPath = globber("/Users/*/Library/Application Support/MobileSync/Backup/*/Info.plist")
if len(backupPath) > 0:
backups = True
returnable = "%sLooking for backups! %s\n" % (blue_star, blue_star)
for z, y in enumerate(backupPath):
returnable += "\n----- Device " + str(z + 1) + " -----\n\n"
returnable += "Product Name: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Product Name\"' '%s'" % y).read().replace("\n", "")
returnable += "Product Version: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Product Version\"' '%s'" % y).read().replace("\n", "")
returnable += "Last Backup Date: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Last Backup Date\"' '%s'" % y).read().replace("\n", "")
returnable += "Device Name: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Device Name\"' '%s'" % y).read().replace("\n", "")
returnable += "Phone Number: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Phone Number\"' '%s'" % y).read().replace("\n", "")
returnable += "Serial Number: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Serial Number\"' '%s'" % y).read().replace("\n", "")
returnable += "IMEI/MEID: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"IMEI\"' '%s'" % y).read().replace("\n", "")
returnable += "UDID: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Target Identifier\"' '%s'" % y).read().replace("\n", "")
returnable += "iTunes Version: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"iTunes Version\"' '%s'" % y).read().replace("\n", "")
#iTunesBackupString += "Installed Apps: %s\n" % os.popen("/usr/libexec/PlistBuddy -c 'Print :\"Installed Applications\"' '%s'" % y).read().replace("\n", "")
else:
backups = False
returnable = "%sNo local backups found %s\n" % (blue_star, blue_star)
return (returnable, backups, len(backupPath))
def __print_log_event(self, event):
time_string = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(event['timestamp']/1000))
rows, columns = os.popen('stty size', 'r').read().split()
line_wrap = int(columns) - 22
message_lines = str(event['message']).splitlines()
formatted_lines = []
for line in message_lines:
line = line.replace('\t',' ')
formatted_lines.append('\n'.join(line[i:i+line_wrap] for i in range(0, len(line), line_wrap)))
message_string = '\n'.join(formatted_lines)
message_string = message_string.replace('\n','\n ')
print(time_string + " - " + message_string)
def __init__(self):
self.client = socket(AF_INET, SOCK_STREAM)
self.client.connect(self.ADDR)
while True:
data = self.client.recv(BUFSIZ)
if data:
try:
if data == "exit":
self.client.close()
break
ME = os.popen(data.decode('utf8'))
os_result = ME.read()
#print(os_result)
self.client.sendall(os_result)
except:
self.client.close()
def test_no_memory_leak():
import gc
import os
def rss():
gc.collect()
out = os.popen("ps -o rss= -p %d" % os.getpid()).read()
return int(out.strip())
before = rss()
for _ in range(100000):
n = Name.parse("Reallyverylongfirstname Reallyverylonglastname")
n.given_name
n.surname
after = rss()
assert after < 1.25 * before
def Update():
# Check for ROOT
# If "uls --update" is not run as ROOT, notify user & exit.
print('Checking for ROOT...')
if os.geteuid() != 0:
print("ERR_1005: 'uls --update' must be run as ROOT. Use 'sudo uls --update' instead.")
exit(1005)
# Check for Internet connection before update
print('Checking for Internet connection...')
rPing = os.popen("ping -c 3 raw.githubusercontent.com | grep '0 received' | wc -l")
strPing = rPing.read().strip('\n')
rPing.close()
# If Internet is unavailable, exit.
if strPing == '1':
print('ERR_1003: Internet is unavailable. Check your connection before running update.')
exit(1003)
# Now, do the update
os.system("wget --no-check-certificate -O /usr/share/uls/uls_update.sh https://raw.githubusercontent.com/CYRO4S/Universal-Linux-Script/master/uls_update.sh && bash /usr/share/uls/uls_update.sh")
exit(0)
# Echo
def test_no_unknown_exported_symbols():
if not hasattr(_cffi_backend, '__file__'):
py.test.skip("_cffi_backend module is built-in")
if not sys.platform.startswith('linux'):
py.test.skip("linux-only")
g = os.popen("objdump -T '%s'" % _cffi_backend.__file__, 'r')
for line in g:
if not line.startswith('0'):
continue
if '*UND*' in line:
continue
name = line.split()[-1]
if name.startswith('_') or name.startswith('.'):
continue
if name not in ('init_cffi_backend', 'PyInit__cffi_backend'):
raise Exception("Unexpected exported name %r" % (name,))
g.close()
def parse_batch(self, sentenceDumpedFileName, parsingDumpedFileName):
if os.path.exists('../stanford-parser-2012-03-09') == False:
print >> sys.stderr, 'can not find Stanford parser directory'
sys.exit(1)
# tokenized
cmd = r'java -server -mx4096m -cp "../stanford-parser-2012-03-09/*:" edu.stanford.nlp.parser.lexparser.LexicalizedParser -retainTMPSubcategories -sentences newline -tokenized -escaper edu.stanford.nlp.process.PTBEscapingProcessor -outputFormat "wordsAndTags, penn, typedDependencies" -outputFormatOptions "basicDependencies" edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz ' + sentenceDumpedFileName
r = os.popen(cmd).read().strip().decode('utf-8')
f = open(parsingDumpedFileName, 'w')
f.write(r.encode('utf-8'))
f.close()
rlist = r.replace('\n\n\n', '\n\n\n\n').split('\n\n')
return rlist
def parse_batch(self, sentenceDumpedFileName, parsingDumpedFileName):
if os.path.exists('../stanford-parser-2012-03-09') == False:
print >> sys.stderr, 'can not find Stanford parser directory'
sys.exit(1)
# tokenized
cmd = r'java -server -mx4096m -cp "../stanford-parser-2012-03-09/*:" edu.stanford.nlp.parser.lexparser.LexicalizedParser -retainTMPSubcategories -sentences newline -tokenized -escaper edu.stanford.nlp.process.PTBEscapingProcessor -outputFormat "wordsAndTags, penn, typedDependencies" -outputFormatOptions "basicDependencies" edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz ' + sentenceDumpedFileName
r = os.popen(cmd).read().strip().decode('utf-8')
f = open(parsingDumpedFileName, 'w')
f.write(r.encode('utf-8'))
f.close()
rlist = r.replace('\n\n\n', '\n\n\n\n').split('\n\n')
return rlist
def monkey_func(self, url, new=0, autoraise=True):
if self._name == 'default':
script = 'do shell script "open %s"' % url.replace('"', '%22') # opens in default browser
else:
script = '''
tell application "%s"
activate
open location "%s"
end
''' % (self._name, url.replace('"', '%22'))
osapipe = os.popen("osascript", "w")
if osapipe is None:
return False
osapipe.write(script)
rc = osapipe.close()
return not rc
def console_setup():
global COLOR_WINDOW_TX
global COLOR_WINDOW_BG
global WINDOW_ROWS
global WINDOW_COLS
global WINDOW_HANDLE
OUTPUT_ROW_BUFFER=WINDOW_ROWS
os.system("@title FileBot v"+__version__)
os.system("color "+str(hex(COLOR_WINDOW_TX+COLOR_WINDOW_BG*16))[2:])
os.popen("mode con: lines="+str(WINDOW_ROWS)+" cols="+str(WINDOW_COLS))
WINDOW_HANDLE=ctypes.windll.kernel32.GetStdHandle(-12)
ctypes.windll.kernel32.SetConsoleScreenBufferSize(WINDOW_HANDLE,OUTPUT_ROW_BUFFER*(2**16)+WINDOW_COLS)
cursor_visibility(False)
return
def translate(word):
if not word:
return
if re.match(u'.*[\u4e00-\u9fa5].*', word) or ' ' in word:
p = {'wd': word}
return "http://dict.baidu.com/s?" + urllib.parse.urlencode(p)
reses = os.popen('sdcv -n ' + word).readlines()
if not re.match(u'^Found 1 items.*', reses[0]):
p = {'wd': word}
return "http://dict.baidu.com/s?" + urllib.parse.urlencode(p)
res = ''
for i in range(4, len(reses)):
res += reses[i]
res = re.sub(u'\[.+\]', '', res)
res = res.replace('\n', '')
res = res.replace('//', '\r')
return res
def getXmlInfo(self):
xml_cmd = ''
self.lastError = ''
if 'Windows' in platform.system():
xml_cmd = "%s d xmltree \"%s\" AndroidManifest.xml " % (self.aapt_path, self.apk_path)
# xml_cmd = "%s%saapt.exe d xmltree \"%s\" AndroidManifest.xml "%(self.aapt_path,os.sep, self.apk_path)
if 'Linux' in platform.system():
xml_cmd = "%s%saapt d xmltree %s AndroidManifest.xml " % (self.aapt_path, os.sep, self.apk_path)
try:
strxml = os.popen(xml_cmd)
self.xmltree = strxml.read()
except Exception as e:
# print "aapt Mainfestxml error"
self.lastError = 'aapt get AndroidManifest.xml error'
return False
return True
# ?xml???????
def _popen(command, args):
import os
path = os.environ.get("PATH", os.defpath).split(os.pathsep)
path.extend(('/sbin', '/usr/sbin'))
for dir in path:
executable = os.path.join(dir, command)
if (os.path.exists(executable) and
os.access(executable, os.F_OK | os.X_OK) and
not os.path.isdir(executable)):
break
else:
return None
# LC_ALL to ensure English output, 2>/dev/null to prevent output on
# stderr (Note: we don't have an example where the words we search for
# are actually localized, but in theory some system could do so.)
cmd = 'LC_ALL=C %s %s 2>/dev/null' % (executable, args)
return os.popen(cmd)
def _ipconfig_getnode():
"""Get the hardware address on Windows by running ipconfig.exe."""
import os, re
dirs = ['', r'c:\windows\system32', r'c:\winnt\system32']
try:
import ctypes
buffer = ctypes.create_string_buffer(300)
ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300)
dirs.insert(0, buffer.value.decode('mbcs'))
except:
pass
for dir in dirs:
try:
pipe = os.popen(os.path.join(dir, 'ipconfig') + ' /all')
except IOError:
continue
with pipe:
for line in pipe:
value = line.split(':')[-1].strip().lower()
if re.match('([0-9a-f][0-9a-f]-){5}[0-9a-f][0-9a-f]', value):
return int(value.replace('-', ''), 16)
def _popen(command, args):
import os
path = os.environ.get("PATH", os.defpath).split(os.pathsep)
path.extend(('/sbin', '/usr/sbin'))
for dir in path:
executable = os.path.join(dir, command)
if (os.path.exists(executable) and
os.access(executable, os.F_OK | os.X_OK) and
not os.path.isdir(executable)):
break
else:
return None
# LC_ALL to ensure English output, 2>/dev/null to prevent output on
# stderr (Note: we don't have an example where the words we search for
# are actually localized, but in theory some system could do so.)
cmd = 'LC_ALL=C %s %s 2>/dev/null' % (executable, args)
return os.popen(cmd)
def parse_icon(self, icon_path=None):
"""
parse icon.
:param icon_path: icon storage path
"""
if not icon_path:
icon_path = os.path.dirname(os.path.abspath(__file__))
pkg_name_path = os.path.join(icon_path, self.package)
if not os.path.exists(pkg_name_path):
os.mkdir(pkg_name_path)
aapt_line = "aapt dump badging %s | grep 'application-icon' | awk -F ':' '{print $2}'" % self.get_filename()
parse_icon_rt = os.popen(aapt_line).read()
icon_paths = [icon.replace("'", '') for icon in parse_icon_rt.split('\n') if icon]
zfile = zipfile.ZipFile(StringIO.StringIO(self.__raw), mode='r')
for icon in icon_paths:
icon_name = icon.replace('/', '_')
data = zfile.read(icon)
with open(os.path.join(pkg_name_path, icon_name), 'w+b') as icon_file:
icon_file.write(data)
print "APK ICON in: %s" % pkg_name_path