def action_inject(self):
"""Inject metadata into a new save file."""
split_filename = os.path.splitext(ntpath.basename(self.in_file))
base_filename = split_filename[0]
extension = split_filename[1]
self.save_options["initialfile"] = (base_filename
+ "_injected" + extension)
self.save_file = tkFileDialog.asksaveasfilename(**self.save_options)
if not self.save_file:
return
self.set_message("Saving file to %s" % ntpath.basename(self.save_file))
# Launch injection on a separate thread after disabling buttons.
self.disable_state()
self.master.after(100, self.action_inject_delay)
python类basename()的实例源码
def browse_picture(self):
self.image = QtGui.QFileDialog.getOpenFileName(None,'OpenFile','c:\\',"Image file(*.png *.jpg)")
self.progressBar.setValue(0)
self.image = str(self.image)
print(self.image)
self.file_name = ntpath.basename(self.image)
self.file_name, ext=os.path.splitext(self.file_name)
self.file_path = ntpath.dirname(self.image)
self.write_path = ntpath.expanduser('~\\Documents\\Document Analysis')
# creating write path if not exists
if not os.path.exists(self.write_path):
os.makedirs(self.write_path)
if self.image:
pixmap = QtGui.QPixmap(self.image)
pixmap = pixmap.scaled(pixmap.width()/5, pixmap.height()/5, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)
#self.labelInputImage.resize(pixmap.width()/4,pixmap.height()/4)
#self.labelInputImage.setPixmap(QtGui.QPixmap(self.image).
# scaled(self.labelInputImage.width(),
# self.labelInputImage.height()))
self.labelInputImage.setPixmap(pixmap)
#self.btnImageBrowse.setEnabled(False)
def askopenfilename(self):
# define options for opening or saving a file
self.file_opt = options = {}
#options['defaultextension'] = '' #'.csv'
#options['filetypes'] = [('all files', '.*'), ('text files', '.csv')]
options['initialdir'] = expanduser(self.filename) if self.filename else expanduser("~")
#options['initialfile'] = ''
options['parent'] = self
options['title'] = 'Choose File to upload'
# get filename
_filename = tkFileDialog.askopenfilename(**self.file_opt)
# open file on your own
if _filename:
self.filename = _filename
self.file_button["text"] = self.filename if (len(self.filename) <= 33) else "...{}".format(self.filename[-30:])
self.s3_name.set(ntpath.basename(self.filename))
def save_images(self, webpage, visuals, image_path):
image_dir = webpage.get_image_dir()
short_path = ntpath.basename(image_path[0])
name = os.path.splitext(short_path)[0]
webpage.add_header(name)
ims = []
txts = []
links = []
for label, image_numpy in visuals.items():
image_name = '%s_%s.png' % (name, label)
save_path = os.path.join(image_dir, image_name)
util.save_image(image_numpy, save_path)
ims.append(image_name)
txts.append(label)
links.append(image_name)
webpage.add_images(ims, txts, links, width=self.win_size)
def send_file(self, filepath):
"""
Send a base64 encoded string to the server.
:param filepath: string path to file
:return: None
"""
_, tail = os.path.split(filepath)
print str(self.username) + " sending out " + str(tail)
fh = open(filepath, 'rb')
content = base64.b64encode(fh.read())
payload = self.new_payload()
payload['content'] = content
payload['type'] = constants.FILE
payload['filename'] = os.path.basename(filepath)
# Send the payload as a binary message by marking binary=True
self.send(str(json.dumps(payload)), True)
# Avoid feedback
time.sleep(0.2)
fh.close()
# self.close()
def interpreter_path(self):
'''
Returns the path for python interpreter, assuming it can be found. Because of various factors (inlcuding ablity to override) this may not be accurate.
'''
if not self.__interpreter_path:
#first try sys.executable--this is reliable most of the time but doesn't work when python is embedded, ex. using wsgi mod for web server
if "python" in os.path.basename(sys.executable):
self.__interpreter_path = sys.executable
#second try sys.prefix and common executable names
else:
possible_path = os.path.join(sys.prefix, "python.exe")
if os.path.exists(possible_path):
self.__interpreter_path = possible_path
possible_path = os.path.join(sys.prefix, "bin", "python")
if os.path.exists(possible_path):
self.__interpreter_path = possible_path
#other options to consider:
#look at some library paths, such as os.__file__, use system path to find python executable that uses that library
#use shell and let it find python. Ex. which python
return self.__interpreter_path
def list_parsers(self):
'''
Retrieve list of parsers
'''
parsers = []
if self.__disablemodulesearch:
#We only look for .py files--it is much better to use regualr module search
parser_file_postfix = self.__parsernamepostfix + '.py'
for fullpath in glob.glob(os.path.join(self.parserdir, '*' + parser_file_postfix)):
basefile = os.path.basename(fullpath)
parsers.append(basefile[:-len(parser_file_postfix)])
else:
for loader, modulename, ispkg in pkgutil.iter_modules():
if not ispkg:
if modulename[-len(self.__parsernamepostfix):] == self.__parsernamepostfix and len(modulename) > len(self.__parsernamepostfix):
parsers.append(modulename[:-len(self.__parsernamepostfix)])
return sorted(parsers, key=lambda s: s.lower())
def save_images(self, webpage, visuals, image_path):
image_dir = webpage.get_image_dir()
short_path = ntpath.basename(image_path[0])
name = os.path.splitext(short_path)[0]
webpage.add_header(name)
ims = []
txts = []
links = []
for label, image_numpy in visuals.items():
image_name = '%s_%s.png' % (name, label)
save_path = os.path.join(image_dir, image_name)
util.save_image(image_numpy, save_path)
ims.append(image_name)
txts.append(label)
links.append(image_name)
webpage.add_images(ims, txts, links, width=self.win_size)
def lookup_user_sids(self):
regapi = registryapi.RegistryApi(self._config)
regapi.set_current("hklm")
key = "Microsoft\\Windows NT\\CurrentVersion\\ProfileList"
val = "ProfileImagePath"
sids = {}
for subkey in regapi.reg_get_all_subkeys(None, key = key):
sid = str(subkey.Name)
path = regapi.reg_get_value(None, key = "", value = val, given_root = subkey)
if path:
path = str(path).replace("\x00", "")
user = ntpath.basename(path)
sids[sid] = user
return sids
def render_text(self, outfd, data):
if self._config.DUMP_DIR == None:
debug.error("Please specify a dump directory (--dump-dir)")
if not os.path.isdir(self._config.DUMP_DIR):
debug.error(self._config.DUMP_DIR + " is not a directory")
for name, buf in data:
## We can use the ntpath module instead of manually replacing the slashes
ofname = ntpath.basename(name)
## Dump the raw event log so it can be parsed with other tools
if self._config.SAVE_EVT:
fh = open(os.path.join(self._config.DUMP_DIR, ofname), 'wb')
fh.write(buf)
fh.close()
outfd.write('Saved raw .evt file to {0}\n'.format(ofname))
## Now dump the parsed, pipe-delimited event records to a file
ofname = ofname.replace(".evt", ".txt")
fh = open(os.path.join(self._config.DUMP_DIR, ofname), 'wb')
for fields in self.parse_evt_info(name, buf):
fh.write('|'.join(fields) + "\n")
fh.close()
outfd.write('Parsed data sent to {0}\n'.format(ofname))
def path_leaf(path):
"""
Get just the filename from the full path.
http://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format
"""
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
def get_file_name(self):
return ntpath.basename(self.checker.path)
def get_file_name(self):
return ntpath.basename(self.code.path)
def upload_policy(self, policy_file_path):
try:
data = {"policy": ""}
files = {'file': (ntpath.basename(policy_file_path), open(policy_file_path, 'rb'),)}
except IOError as e:
return WebInspectResponse(success=False,
message="There was an error while handling the request{}.".format(e))
# hack. doing this avoids us later specifying a content-type of application/json. needs a refactor
headers = {
'Accept': 'application/json'
}
return self._request('POST', '/webinspect/securebase/policy', data=data, files=files, headers=headers)
def upload_settings(self, settings_file_path):
try:
data = {"scanSettings": ""}
files = {'file': (ntpath.basename(settings_file_path), open(settings_file_path, 'rb'),)}
except IOError as e:
return WebInspectResponse(success=False,
message="There was an error while handling the request{}.".format(e))
return self._request('PUT', '/webinspect/scanner/settings', data=data, files=files)
def upload_webmacro(self, macro_file_path):
try:
files = {'macro': (ntpath.basename(macro_file_path), open(macro_file_path, 'rb'))}
except IOError as e:
return WebInspectResponse(success=False, message="Could not read file to upload {}.".format(e))
return self._request('PUT', '/webinspect/scanner/macro', files=files)
def slice_image(self, source_image, tile_width, tile_height):
if not os.path.isfile(source_image):
self.logger.error('file {} does not exist'.format(source_image))
exit(1)
file = open(source_image, 'rb')
with Image.open(file) as image:
cwd = os.getcwd()
basename = strftime("slice_%Y-%m-%d_%H-%M-%S", gmtime())
directory = os.path.join(cwd, basename)
self.logger.info('slicing picture {} into tiles'.format(source_image))
tiles = make_tiles(image, tile_width=tile_width, tile_height=tile_height)
store_tiles(tiles, directory)
self.logger.info('picture sliced into {} tiles {}'.format(len(tiles), directory))
def _get_filename(self, path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)
def post_localfile(roomId, encoded_photo, text='', html='', markdown='', toPersonId='', toPersonEmail=''):
filename='/app/output.jpg'
with open(filename, 'wb') as handle:
handle.write(encoded_photo.decode('base64'))
openfile = open(filename, 'rb')
filename = ntpath.basename(filename)
payload = {'roomId': roomId, 'files': (filename, openfile, 'image/jpg')}
#payload = {'roomId': roomId}
if text:
payload['text'] = text
if html:
payload['html'] = html
if markdown:
payload['markdown'] = markdown
if toPersonId:
payload['toPersonId'] = toPersonId
if toPersonEmail:
payload['toPersonEmail'] = toPersonEmail
m = MultipartEncoder(fields=payload)
headers = {'Authorization': "Bearer " + spark_token, 'Content-Type': m.content_type}
page = requests.request("POST",url=spark_host + "v1/messages", data=m, headers = headers )
sys.stderr.write( "page: "+str(page)+"\n" )
message=page.json()
file_dict = json.loads(page.text)
file_dict['statuscode'] = str(page.status_code)
sys.stderr.write( "statuscode: "+str(file_dict['statuscode'])+"\n" )
sys.stderr.write( "file_dict: "+str(file_dict)+"\n" )
handle.close()
openfile.close()
return message
def post_pdffile(roomId, encoded_file, text='', html='', markdown='', toPersonId='', toPersonEmail=''):
filename='/app/output.pdf'
with open(filename, 'wb') as handle:
handle.write(encoded_file.decode('base64'))
openfile = open(filename, 'rb')
filename = ntpath.basename(filename)
payload = {'roomId': roomId, 'files': (filename, openfile, 'application/pdf')}
#payload = {'roomId': roomId}
if text:
payload['text'] = text
if html:
payload['html'] = html
if markdown:
payload['markdown'] = markdown
if toPersonId:
payload['toPersonId'] = toPersonId
if toPersonEmail:
payload['toPersonEmail'] = toPersonEmail
m = MultipartEncoder(fields=payload)
headers = {'Authorization': "Bearer " + spark_token, 'Content-Type': m.content_type}
page = requests.request("POST",url=spark_host + "v1/messages", data=m, headers = headers )
sys.stderr.write( "page: "+str(page)+"\n" )
message=page.json()
file_dict = json.loads(page.text)
file_dict['statuscode'] = str(page.status_code)
sys.stderr.write( "statuscode: "+str(file_dict['statuscode'])+"\n" )
sys.stderr.write( "file_dict: "+str(file_dict)+"\n" )
handle.close()
openfile.close()
return message