本文整理汇总了Python中os.linesep方法的典型用法代码示例。如果您正苦于以下问题:Python os.linesep方法的具体用法?Python os.linesep怎么用?Python os.linesep使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.linesep方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_write_exclusive_text_file
# 需要导入模块: import os [as 别名]
# 或者: from os import linesep [as 别名]
def test_write_exclusive_text_file(smb_share):
file_path = "%s\\%s" % (smb_share, "file.txt")
file_contents = u"File Contents\nNewline"
with smbclient.open_file(file_path, mode='x') as fd:
assert isinstance(fd, io.TextIOWrapper)
assert fd.closed is False
with pytest.raises(IOError):
fd.read()
assert fd.tell() == 0
fd.write(file_contents)
assert int(fd.tell()) == (len(file_contents) - 1 + len(os.linesep))
assert fd.closed is True
with smbclient.open_file(file_path, mode='r') as fd:
assert fd.read() == file_contents
with pytest.raises(OSError, match=re.escape("[NtStatus 0xc0000035] File exists: ")):
smbclient.open_file(file_path, mode='x')
assert fd.closed is True
示例2: write_config
# 需要导入模块: import os [as 别名]
# 或者: from os import linesep [as 别名]
def write_config(root=None):
if root and os.name == 'nt':
root = root.replace('\\', '/') # For Windows
if root and platform.system().startswith('CYGWIN'): # For cygwin
if root.startswith('/usr/lib'):
cygwin_root = os.popen('cygpath -w /').read().strip().replace('\\', '/')
root = cygwin_root + root[len('/usr'):]
elif STATIC_ROOT.startswith('/cygdrive'):
driver = STATIC_ROOT.split('/')
cygwin_driver = '/'.join(driver[:3])
win_driver = driver[2].upper() + ':'
root = root.replace(cygwin_driver, win_driver)
content = []
with open_(PATH_CONFIG, encoding='utf-8') as f:
for line in f:
if root:
if line.startswith('root'):
line = 'root={}{}'.format(root, os.linesep)
content.append(line)
with open_(PATH_CONFIG, 'w', encoding='utf-8') as f:
f.writelines(content)
示例3: logmsg
# 需要导入模块: import os [as 别名]
# 或者: from os import linesep [as 别名]
def logmsg(request,type,message,args):
is_dst = time.daylight and time.localtime().tm_isdst > 0
tz = - (time.altzone if is_dst else time.timezone) / 36
if tz>=0:
tz="+%04d"%tz
else:
tz="%05d"%tz
datestr = '%d/%b/%Y %H:%M:%S'
user = getattr(logStore,'user','')
isValid = getattr(logStore,'isValid','')
code = getattr(logStore,'code','')
args = getLogDateTime(args)
log = '%s %s,%s,%s,%s,%s,%s' % (datetime.now().strftime(datestr),tz,request.address_string(),user,isValid,code, message % args)
with logLock:
with open(cfg.logpath,'a') as fw:
fw.write(log+os.linesep)
return log
示例4: print_settings
# 需要导入模块: import os [as 别名]
# 或者: from os import linesep [as 别名]
def print_settings(self):
logger.info("{}---### Start of User Settings ###---".format(os.linesep))
logger.info('Arguments:')
logger.info("\tInput_fMRI: {}".format(self.func_4D))
logger.info('\t\tNumber of TRs: {}'.format(self.num_TR))
logger.info('\t\tTR(ms): {}'.format(self.TR_in_ms))
logger.info("\tCIFTIFY_WORKDIR: {}".format(self.work_dir))
logger.info("\tSubject: {}".format(self.subject.id))
logger.info("\tfMRI Output Label: {}".format(self.fmri_label))
logger.info("\t{}".format(self.func_ref.descript))
logger.info("\tSurface Registration Sphere: {}".format(self.surf_reg))
logger.info("\tT1w intermiadate for registation: {}".format(self.registered_to_this_T1w))
if self.smoothing.sigma > 0:
logger.info("\tSmoothingFWHM: {}".format(self.smoothing.fwhm))
logger.info("\tSmoothing Sigma: {}".format(self.smoothing.sigma))
else:
logger.info("\tNo smoothing will be applied")
if self.dilate_percent_below:
logger.info("\tWill fill holes defined as data with intensity below {} percentile".format(self.dilate_percent_below))
logger.info('\tMulthreaded subprocesses with use {} threads'.format(self.n_cpus))
logger.info("{}---### End of User Settings ###---".format(os.linesep))
logger.info("\nThe following settings are set by default:")
logger.info("\tGrayordinatesResolution: {}".format(self.grayord_res))
logger.info('\tLowResMesh: {}k'.format(self.low_res))
示例5: write_cras_file
# 需要导入模块: import os [as 别名]
# 或者: from os import linesep [as 别名]
def write_cras_file(freesurfer_folder, cras_mat):
'''read info about the surface affine matrix from freesurfer output and
write it to a tmpfile'''
mri_info = get_stdout(['mri_info', os.path.join(freesurfer_folder, 'mri',
'brain.finalsurfs.mgz')])
for line in mri_info.split(os.linesep):
if 'c_r' in line:
bitscr = line.split('=')[4]
matrix_x = bitscr.replace(' ','')
elif 'c_a' in line:
bitsca = line.split('=')[4]
matrix_y = bitsca.replace(' ','')
elif 'c_s' in line:
bitscs = line.split('=')[4]
matrix_z = bitscs.replace(' ','')
with open(cras_mat, 'w') as cfile:
cfile.write('1 0 0 {}\n'.format(matrix_x))
cfile.write('0 1 0 {}\n'.format(matrix_y))
cfile.write('0 0 1 {}\n'.format(matrix_z))
cfile.write('0 0 0 1{}\n')
示例6: wb_command_version
# 需要导入模块: import os [as 别名]
# 或者: from os import linesep [as 别名]
def wb_command_version():
'''
Returns version info about wb_command.
Will raise an error if wb_command is not found, since the scripts that use
this depend heavily on wb_command and should crash anyway in such
an unexpected situation.
'''
wb_path = find_workbench()
if wb_path is None:
raise EnvironmentError("wb_command not found. Please check that it is "
"installed.")
wb_help = util.check_output('wb_command')
wb_version = wb_help.split(os.linesep)[0:3]
sep = '{} '.format(os.linesep)
wb_v = sep.join(wb_version)
all_info = 'wb_command:{0}Path: {1}{0}{2}'.format(sep,wb_path,wb_v)
return(all_info)
示例7: freesurfer_version
# 需要导入模块: import os [as 别名]
# 或者: from os import linesep [as 别名]
def freesurfer_version():
'''
Returns version info for freesurfer
'''
fs_path = find_freesurfer()
if fs_path is None:
raise EnvironmentError("Freesurfer cannot be found. Please check that "
"it is installed.")
try:
fs_buildstamp = os.path.join(os.path.dirname(fs_path),
'build-stamp.txt')
with open(fs_buildstamp, "r") as text_file:
bstamp = text_file.read()
except:
return "freesurfer build information not found."
bstamp = bstamp.replace(os.linesep,'')
info = "freesurfer:{0}Path: {1}{0}Build Stamp: {2}".format(
'{} '.format(os.linesep),fs_path, bstamp)
return info
示例8: fsl_version
# 需要导入模块: import os [as 别名]
# 或者: from os import linesep [as 别名]
def fsl_version():
'''
Returns version info for FSL
'''
fsl_path = find_fsl()
if fsl_path is None:
raise EnvironmentError("FSL not found. Please check that it is "
"installed")
try:
fsl_buildstamp = os.path.join(fsl_path, 'etc',
'fslversion')
with open(fsl_buildstamp, "r") as text_file:
bstamp = text_file.read()
except:
return "FSL build information not found."
bstamp = bstamp.replace(os.linesep,'')
info = "FSL:{0}Path: {1}{0}Version: {2}".format('{} '.format(os.linesep),
fsl_path, bstamp)
return info
示例9: get_penn_treebank
# 需要导入模块: import os [as 别名]
# 或者: from os import linesep [as 别名]
def get_penn_treebank() -> Dict[str, List[str]]:
url = 'https://raw.githubusercontent.com/wojzaremba/lstm/master/data/ptb.{}.txt'
root = download.get_cache_directory(os.path.join('datasets', 'ptb'))
def creator(path):
dataset = {}
for split in ('train', 'dev', 'test'):
data_path = gdown.cached_download(url.format(split if split != 'dev' else 'valid'))
with io.open(data_path, 'rt') as f:
dataset[split] = [line.rstrip(os.linesep) for line in f]
with io.open(path, 'wb') as f:
pickle.dump(dataset, f)
return dataset
def loader(path):
with io.open(path, 'rb') as f:
return pickle.load(f)
pkl_path = os.path.join(root, 'ptb.pkl')
return download.cache_or_load_file(pkl_path, creator, loader)
示例10: get_small_parallel_enja
# 需要导入模块: import os [as 别名]
# 或者: from os import linesep [as 别名]
def get_small_parallel_enja() -> Dict[str, Tuple[List[str]]]:
en_url = 'https://raw.githubusercontent.com/odashi/small_parallel_enja/master/{}.en'
ja_url = 'https://raw.githubusercontent.com/odashi/small_parallel_enja/master/{}.ja'
root = download.get_cache_directory(os.path.join('datasets', 'small_parallel_enja'))
def creator(path):
dataset = {}
for split in ('train', 'dev', 'test'):
en_path = gdown.cached_download(en_url.format(split))
ja_path = gdown.cached_download(ja_url.format(split))
with io.open(en_path, 'rt') as en, io.open(ja_path, 'rt') as ja:
dataset[split] = [(x.rstrip(os.linesep), y.rstrip(os.linesep))
for x, y in zip(en, ja)]
with io.open(path, 'wb') as f:
pickle.dump(dataset, f)
return dataset
def loader(path):
with io.open(path, 'rb') as f:
return pickle.load(f)
pkl_path = os.path.join(root, 'enja.pkl')
return download.cache_or_load_file(pkl_path, creator, loader)
示例11: ShowUsage
# 需要导入模块: import os [as 别名]
# 或者: from os import linesep [as 别名]
def ShowUsage():
print 'Usage: %s -c CONFIG_FILE_1 -c CONFIG_FILE_2 [...] -c CONFIG_FILE_n -u FORWARDINGURL -f LOCALHOST1:LOCALPORT1/TARGETHOST1:TARGETPORT1 -f LOCALHOST2:LOCALPORT2/TARGETHOST2:TARGETPORT2 [...] LOCALHOSTn:LOCALPORTn/TARGETHOSTn:TARGETPORTn [--debug]' % (sys.argv[0])
print os.linesep
print 'Example: %s -c CONFIG_FILE_1 -u https://vulnerableserver/EStatus/ -f 127.0.0.1:28443/10.10.20.11:8443' % (sys.argv[0])
print os.linesep
print 'Example: %s -c CONFIG_FILE_1 -c CONFIG_FILE_2 -u https://vulnerableserver/EStatus/ -f 127.0.0.1:135/10.10.20.37:135 -f 127.0.0.1:139/10.10.20.37:139 -f 127.0.0.1:445/10.10.20.37:445' % (sys.argv[0])
print os.linesep
print 'Data from configuration files is applied in sequential order, to allow partial customization files to be overlayed on top of more complete base files.'
print os.linesep
print 'IE if the same parameter is defined twice in the same file, the later value takes precedence, and if it is defined in two files, the value in whichever file is specified last on the command line takes precedence.'
print os.linesep
print '--debug will enable verbose output.'
print os.linesep
print '--unsafetls will disable TLS/SSL certificate validation when connecting to the server, if the connection is over HTTPS'
# logging-related options not mentioned because file output is buggy - just redirect stdout to a file instead
#print os.linesep
#print '--log LOGFILEPATH will cause all output to be written to the specified file (as well as the console, unless --quiet is also specified).'
#print os.linesep
#print '--quiet will suppress console output (but still allow log file output if that option is enabled).'
示例12: ShowUsage
# 需要导入模块: import os [as 别名]
# 或者: from os import linesep [as 别名]
def ShowUsage():
print 'This utility generates a configuration file and matching server-side code (JSP, etc.) to be used with the ABPTTS client component.'
print os.linesep
print 'Usage: %s -c CONFIG_FILE_1 -c CONFIG_FILE_2 [...] -c CONFIG_FILE_n -o BASE_OUTPUT_DIRECTORY [--output-filename OUTPUT_CONFIG_FILE] [-w OUTPUT_WRAPPER_TEMLATE_FILE] [--ignore-defaults] [--wordlist WORDLIST_FILE] [--debug]' % (sys.argv[0])
print os.linesep
print 'Example: %s -c CONFIG_FILE_1 -o /home/blincoln/abptts/config/10.87.134.12' % (sys.argv[0])
print os.linesep
print 'Example: %s -c CONFIG_FILE_1 -c CONFIG_FILE_2 -o /home/blincoln/abptts/config/supervulnerable.goingtogethacked.internet' % (sys.argv[0])
print os.linesep
print 'Data from configuration files is applied in sequential order, to allow partial customization files to be overlayed on top of more complete base files.'
print os.linesep
print 'IE if the same parameter is defined twice in the same file, the later value takes precedence, and if it is defined in two files, the value in whichever file is specified last on the command line takes precedence.'
print os.linesep
print '--output-filename specifies an alternate output filename for the configuration (as opposed to the default of "config.txt")'
print os.linesep
print '-w specifies a template file to use for generating the response wrapper prefix/suffix - see the documentation for details'
print os.linesep
print '--ignore-defaults prevents loading the default configuration as the base. For example, use this mode to merge two or more custom configuration overlay files without including options not explicitly defined in them. IMPORTANT: this will disable generation of server-side files (because if the defaults are not available, it would be very complicated to determine if all necessary parameters have been specified).'
print os.linesep
print '--wordlist allows specification of a custom wordlist file (for random parameter name/value generation) instead of the default.'
print os.linesep
print '--debug will enable verbose output.'
示例13: test_rawdump_header_seek_offset
# 需要导入模块: import os [as 别名]
# 或者: from os import linesep [as 别名]
def test_rawdump_header_seek_offset(self):
fh = open(SAMPLE_RAWDUMP_HEADER, 'rt')
header = gsb.GSBHeader.fromfile(fh, verify=True)
# Includes 1 trailing blank space, one line separator
header_nbytes = header.nbytes
assert (header_nbytes
== len(' '.join(header.words) + ' ' + os.linesep))
assert header.seek_offset(1) == header_nbytes
assert header.seek_offset(12) == 12 * header_nbytes
# Note that text pointers can't seek from current position.
# Seek 2nd header.
fh.seek(header.seek_offset(1))
header1 = gsb.GSBHeader.fromfile(fh, verify=True)
assert abs(header1.time
- Time('2015-04-27T13:15:00.251658480')) < 1.*u.ns
fh.seek(header.seek_offset(9))
header2 = gsb.GSBHeader.fromfile(fh, verify=True)
assert abs(header2.time
- Time('2015-04-27T13:15:02.264924400')) < 1.*u.ns
fh.close()
示例14: _handle_apply_patches
# 需要导入模块: import os [as 别名]
# 或者: from os import linesep [as 别名]
def _handle_apply_patches(self, message):
for patch in message.patch_list:
start = patch["oldStart"]
end = patch["oldEnd"]
text = patch["newText"]
target_buffer_contents = self._target_buffer[:]
before_in_new_line = target_buffer_contents[start["row"]][:start["column"]]
after_in_new_line = target_buffer_contents[end["row"]][end["column"]:]
new_lines = text.split(os.linesep)
if len(new_lines) > 0:
new_lines[0] = before_in_new_line + new_lines[0]
else:
new_lines = [before_in_new_line]
new_lines[-1] = new_lines[-1] + after_in_new_line
self._target_buffer[start["row"] : end["row"] + 1] = new_lines
self._buffer_contents = self._target_buffer[:]
self._vim.command(":redraw")
示例15: test_spinner_report
# 需要导入模块: import os [as 别名]
# 或者: from os import linesep [as 别名]
def test_spinner_report(capfd, monkeypatch):
monkeypatch.setattr(sys.stdout, "isatty", lambda: False)
with spinner.Spinner(refresh_rate=100) as spin:
spin.stream.write(os.linesep)
spin.add("ok")
spin.add("fail")
spin.add("skip")
spin.succeed("ok")
spin.fail("fail")
spin.skip("skip")
out, err = capfd.readouterr()
lines = out.split(os.linesep)
del lines[0]
expected = [
"\r{}✔ OK ok in 0.0 seconds".format(spin.CLEAR_LINE),
"\r{}✖ FAIL fail in 0.0 seconds".format(spin.CLEAR_LINE),
"\r{}⚠ SKIP skip in 0.0 seconds".format(spin.CLEAR_LINE),
"\r{}".format(spin.CLEAR_LINE),
]
assert lines == expected
assert not err