本文整理汇总了Python中path.Path方法的典型用法代码示例。如果您正苦于以下问题:Python path.Path方法的具体用法?Python path.Path怎么用?Python path.Path使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类path
的用法示例。
在下文中一共展示了path.Path方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_6_regenerate
# 需要导入模块: import path [as 别名]
# 或者: from path import Path [as 别名]
def test_6_regenerate(self):
self.getPage('/testStr')
# grab the cookie ID
id1 = self.cookies[0][1].split(';', 1)[0].split('=', 1)[1]
self.getPage('/regen')
assert self.body == b'logged in'
id2 = self.cookies[0][1].split(';', 1)[0].split('=', 1)[1]
assert id1 != id2
self.getPage('/testStr')
# grab the cookie ID
id1 = self.cookies[0][1].split(';', 1)[0].split('=', 1)[1]
self.getPage('/testStr',
headers=[
('Cookie',
'session_id=maliciousid; '
'expires=Sat, 27 Oct 2017 04:18:28 GMT; Path=/;')])
id2 = self.cookies[0][1].split(';', 1)[0].split('=', 1)[1]
assert id1 != id2
assert id2 != 'maliciousid'
示例2: dump_trace
# 需要导入模块: import path [as 别名]
# 或者: from path import Path [as 别名]
def dump_trace(self):
filename = QtWidgets.QFileDialog.getSaveFileName()[0]
filepath = Path(filename)
if not filepath.exists() and filepath != '':
try:
index = self.traces_tab.currentIndex()
trace = self.core.traces[self.id_map[index]]
f = filepath.open("w")
for line in trace.to_string_generator():
f.write(line+"\n")
f.close()
print "Writing done"
except KeyError:
print "Trace not found"
else:
print "File already exists.. (do not dump)"
示例3: export_result
# 需要导入模块: import path [as 别名]
# 或者: from path import Path [as 别名]
def export_result(self, _):
filename = QtWidgets.QFileDialog.getSaveFileName()[0]
filepath = Path(filename)
if not filepath.exists() and filepath != '':
report = filepath if filepath.ext == ".html" else filepath.dirname() / filepath.namebase+".html"
raw = filepath.dirname() / filepath.namebase+".csv"
html_file = filepath.dirname() / filepath.namebase+".html"
html_file.write_bytes(self.report.generate())
report.write_text(self.report.generate())
f = raw.open("w")
for addr, infos in self.results.iteritems():
f.write_bytes(u"0x%x,%s,%d,%s,0x%x,0x%x\n" % (addr, to_status_name(infos.status), infos.k,
infos.dependency, infos.alive_branch, infos.dead_branch))
f.close()
self.log("[info]", "Export done in %s and %s" % (report.basename(), raw.basename()))
else:
self.log("[error]", "File already exists.. (do not save)")
示例4: logging_success
# 需要导入模块: import path [as 别名]
# 或者: from path import Path [as 别名]
def logging_success(
self, source: Union[str, Path], table_name: str, is_create_table: bool
) -> None:
table_schema = self.__schema_extractor.fetch_table_schema(table_name.strip())
self.__result_counter.inc_success(is_create_table)
self.__logger.info(
"convert '{source:s}' to '{table_info:s}' table".format(
source=cyan(source),
table_info=bright(
green(
table_schema.dumps(
output_format="text", verbosity_level=self.__verbosity_level
)
)
),
)
)
示例5: getCourseDir
# 需要导入模块: import path [as 别名]
# 或者: from path import Path [as 别名]
def getCourseDir(cid, dtstr, basedir='', known_course_ids=None, is_edge=False):
cdir = path(basedir)
if is_edge:
cdir = cdir / "EDGE"
if not cdir.exists():
os.mkdir(cdir)
else:
if not cid in known_course_ids or []:
cdir = cdir / "UNKNOWN"
if not cdir.exists():
os.mkdir(cdir)
cdir = cdir / (cid.replace('/','-'))
if not cdir.exists():
os.mkdir(cdir)
cdir2 = cdir / dtstr
if not cdir2.exists():
os.mkdir(cdir2)
return cdir2
示例6: cleanup_rows_from_grade_persistent
# 需要导入模块: import path [as 别名]
# 或者: from path import Path [as 别名]
def cleanup_rows_from_grade_persistent(csvfn, tempfn, field_to_fix="passed_timestamp"):
"""
Removes the null values from grades_persistentcoursegrade.csv.gz.
The function also fixes course ids by changing them from their
edX URL format to their usual format. For instance,
course-v1:MITx+STL.162x+2T2017 should be MITx/STL.162x/2T2017.
This operation permanently modifies the CSV.
:param csvfn: The path of the csv.gz to be modified
:param tempfn: The path of the temporary csv.gz
:type csvfn: str
:type tempfn: str
"""
with gzip.open(csvfn, "r") as open_csv:
csv_dict = csv.DictReader(open_csv)
with gzip.open(tempfn, "w+") as write_csv_file:
write_csv = csv.DictWriter(write_csv_file, fieldnames=csv_dict.fieldnames)
write_csv.writeheader()
for row in csv_dict:
row_dict = remove_nulls_from_row(row, field_to_fix)
row_dict = fix_course_ids(row_dict)
write_csv.writerow(row_dict)
os.rename(tempfn, csvfn)
示例7: read_scene_data
# 需要导入模块: import path [as 别名]
# 或者: from path import Path [as 别名]
def read_scene_data(data_root, sequence_set, seq_length=3, step=1):
data_root = Path(data_root)
im_sequences = []
poses_sequences = []
indices_sequences = []
demi_length = (seq_length - 1) // 2
shift_range = np.array([step*i for i in range(-demi_length, demi_length + 1)]).reshape(1, -1)
sequences = set()
for seq in sequence_set:
corresponding_dirs = set((data_root/'sequences').dirs(seq))
sequences = sequences | corresponding_dirs
print('getting test metadata for theses sequences : {}'.format(sequences))
for sequence in tqdm(sequences):
poses = np.genfromtxt(data_root/'poses'/'{}.txt'.format(sequence.name)).astype(np.float64).reshape(-1, 3, 4)
imgs = sorted((sequence/'image_2').files('*.png'))
# construct 5-snippet sequences
tgt_indices = np.arange(demi_length, len(imgs) - demi_length).reshape(-1, 1)
snippet_indices = shift_range + tgt_indices
im_sequences.append(imgs)
poses_sequences.append(poses)
indices_sequences.append(snippet_indices)
return im_sequences, poses_sequences, indices_sequences
示例8: configure_from_directory
# 需要导入模块: import path [as 别名]
# 或者: from path import Path [as 别名]
def configure_from_directory(self, directory):
"""
Load configuration files from the config_root
and one or more queue configurations from a conf.d
directory relative to the config_root
"""
directory = Path(directory)
log_config = directory / 'logging.json'
if log_config.exists():
with open(log_config) as config:
logging.config.dictConfig(json.load(config))
else:
logging.basicConfig(level="DEBUG")
self.log = logging.getLogger('xqueue_watcher.manager')
app_config_path = directory / 'xqwatcher.json'
self.manager_config = get_manager_config_values(app_config_path)
confd = directory / 'conf.d'
for watcher in confd.files('*.json'):
with open(watcher) as queue_config:
self.configure(json.load(queue_config))
示例9: update_from_data_xy
# 需要导入模块: import path [as 别名]
# 或者: from path import Path [as 别名]
def update_from_data_xy(self, xy, ignore=None, updatex=True, updatey=True):
"""
Update the bounds of the :class:`Bbox` based on the passed in
data. After updating, the bounds will have positive *width*
and *height*; *x0* and *y0* will be the minimal values.
*xy*: a numpy array of 2D points
*ignore*:
- when True, ignore the existing bounds of the :class:`Bbox`.
- when False, include the existing bounds of the :class:`Bbox`.
- when None, use the last value passed to :meth:`ignore`.
*updatex*: when True, update the x values
*updatey*: when True, update the y values
"""
if len(xy) == 0:
return
path = Path(xy)
self.update_from_path(path, ignore=ignore,
updatex=updatex, updatey=updatey)
示例10: write_examples
# 需要导入模块: import path [as 别名]
# 或者: from path import Path [as 别名]
def write_examples(maker):
maker.set_indent_level(0)
maker.write_chapter("Examples")
examples_root = Path("pages").joinpath("examples")
maker.inc_indent_level()
maker.write_chapter("Load a CSV table")
maker.write_file(examples_root.joinpath("load_csv.txt"))
maker.write_chapter("Get loaded table data as pandas.DataFrame instance")
maker.write_file(examples_root.joinpath("as_dataframe.txt"))
maker.write_chapter("For more information")
maker.write_lines(
[
"More examples are available at ",
"https://{:s}.rtfd.io/en/latest/pages/examples/index.html".format(PROJECT_NAME),
]
)
示例11: test_normal_multibyte
# 需要导入模块: import path [as 别名]
# 或者: from path import Path [as 别名]
def test_normal_multibyte(
self, tmpdir, test_id, table_text, filename, encoding, headers, expected
):
file_path = Path(str(tmpdir.join(filename)))
file_path.parent.makedirs_p()
with open(file_path, "w", encoding=encoding) as f:
f.write(table_text)
loader = ptr.CsvTableFileLoader(file_path)
loader.headers = headers
for tabledata in loader.load():
print("test-id={}".format(test_id))
print(dumps_tabledata(tabledata))
assert tabledata.in_tabledata_list(expected)
示例12: test_7_session_cookies
# 需要导入模块: import path [as 别名]
# 或者: from path import Path [as 别名]
def test_7_session_cookies(self):
self.getPage('/set_session_cls/cherrypy.lib.sessions.RamSession')
self.getPage('/clear')
self.getPage('/session_cookie')
# grab the cookie ID
cookie_parts = dict([p.strip().split('=')
for p in self.cookies[0][1].split(';')])
# Assert there is no 'expires' param
assert set(cookie_parts.keys()) == {'temp', 'Path'}
id1 = cookie_parts['temp']
assert list(sessions.RamSession.cache) == [id1]
# Send another request in the same "browser session".
self.getPage('/session_cookie', self.cookies)
cookie_parts = dict([p.strip().split('=')
for p in self.cookies[0][1].split(';')])
# Assert there is no 'expires' param
assert set(cookie_parts.keys()) == {'temp', 'Path'}
assert self.body.decode('utf-8') == id1
assert list(sessions.RamSession.cache) == [id1]
# Simulate a browser close by just not sending the cookies
self.getPage('/session_cookie')
# grab the cookie ID
cookie_parts = dict([p.strip().split('=')
for p in self.cookies[0][1].split(';')])
# Assert there is no 'expires' param
assert set(cookie_parts.keys()) == {'temp', 'Path'}
# Assert a new id has been generated...
id2 = cookie_parts['temp']
assert id1 != id2
assert set(sessions.RamSession.cache.keys()) == {id1, id2}
# Wait for the session.timeout on both sessions
time.sleep(2.5)
cache = list(sessions.RamSession.cache)
if cache:
if cache == [id2]:
self.fail('The second session did not time out.')
else:
self.fail('Unknown session id in cache: %r', cache)
示例13: add_trace
# 需要导入模块: import path [as 别名]
# 或者: from path import Path [as 别名]
def add_trace(self, t):
index = self.core.add_trace(t)
self.analysis_widget.trace_selector.addItem("#%d %s" % (index, Path(t.filename).name))
return index
示例14: remove_trace
# 需要导入模块: import path [as 别名]
# 或者: from path import Path [as 别名]
def remove_trace(self, tr_id):
tr = self.core.traces[tr_id]
index = self.analysis_widget.trace_selector.findText("#%d %s" % (tr_id, Path(tr.filename).name))
self.analysis_widget.trace_selector.removeItem(index)
self.core.remove_trace(tr_id)
示例15: trace_switch
# 需要导入模块: import path [as 别名]
# 或者: from path import Path [as 别名]
def trace_switch(self, index, trace=None):
try:
trace = self.core.traces[self.id_map[index]] if trace is None else trace
fname = Path(trace.filename).name
length = trace.length()
uniq = len(trace.addr_covered)
try:
coverage = (uniq * 100) / self.core.nb_instr
except ZeroDivisionError:
coverage = -1
self.trace_infos.setText(("Name:%s\nLength:%d\nUnique instr:%d\nCoverage:%d%c" %
(fname, length, uniq, coverage, '%')))
except KeyError: # Upon tab creation callback called while id_map not yet filled
pass