本文整理汇总了Python中os.write函数的典型用法代码示例。如果您正苦于以下问题:Python write函数的具体用法?Python write怎么用?Python write使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了write函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_runcmd_redirects_stdin_from_file
def test_runcmd_redirects_stdin_from_file(self):
fd, filename = tempfile.mkstemp()
os.write(fd, 'foobar')
os.lseek(fd, 0, os.SEEK_SET)
self.assertEqual(cliapp.runcmd_unchecked(['cat'], stdin=fd),
(0, 'foobar', ''))
os.close(fd)
示例2: child
def child(pipeout):
zzz = 0
while True:
time.sleep(1 if zzz == 0 else zzz)
msg = ('Spam %03d' % zzz).encode()
os.write(pipeout, msg)
zzz = (zzz+1) % 5
示例3: save_data
def save_data(data, output_filename):
"""
Save data to file.
If the file already exists, the function will not save the data and return
1
Parameters
----------
data : str
String containing the data you wish to write out to a file
output_filename : str
Path (full or relative) to the file you will save the data into.
Returns
-------
out : int
Return 0 if the data was saved successfully. Return 1 if the file
already exists.
Hint
----
Check out the os module for determining whether a file exists already.
"""
if not os.path.exists(output_filename): # output_file doesn't currently exist
fd = os.open(output_filename,os.O_WRONLY|os.O_CREAT)
os.write(fd,data)
os.close(fd)
return 0
else:
return 1
示例4: create_signed_cert
def create_signed_cert(self, ou, san="IP:127.0.0.1,IP:::1,DNS:localhost"):
print_ok("generating {0}.key, {0}.crt, {0}.p12".format(ou))
fd, openssl_config = mkstemp(dir='.')
os.write(fd, "extendedKeyUsage=clientAuth,serverAuth\n".encode('utf-8'))
os.write(fd, "subjectAltName = {0}".format(san).encode('utf-8'))
call("openssl genrsa -out {0}.key 1024".format(ou),
shell=True, stderr=FNULL)
call(
"openssl req -new -key {0}.key -out {0}.csr -subj /C=US/ST=CA/O=ghostunnel/OU={0}".format(ou),
shell=True,
stderr=FNULL)
call("chmod 600 {0}.key".format(ou), shell=True)
call(
"openssl x509 -req -in {0}.csr -CA {1}.crt -CAkey {1}.key -CAcreateserial -out {0}_temp.crt -days 5 -extfile {2}".format(
ou,
self.name,
openssl_config),
shell=True,
stderr=FNULL)
call(
"openssl pkcs12 -export -out {0}_temp.p12 -in {0}_temp.crt -inkey {0}.key -password pass:".format(ou),
shell=True)
os.rename("{0}_temp.crt".format(ou), "{0}.crt".format(ou))
os.rename("{0}_temp.p12".format(ou), "{0}.p12".format(ou))
os.close(fd)
os.remove(openssl_config)
self.leaf_certs.append(ou)
示例5: _write
def _write(root, path, buf, offset, fh):
f_path = full_path(root, path)
vnfs_ops = VNFSOperations(root)
file_name = vnfs_ops.vnfs_get_file_name(f_path)
#if file_name == "action":
if file_name in special_files and special_files[file_name]+'_write' in globals():
try:
nf_config = get_nf_config(vnfs_ops, f_path)
# call the custom write function
logger.info('Writing to ' + file_name + ' in ' +
nf_config['nf_instance_name'] + '@' + nf_config['host'])
ret_str = globals()[special_files[file_name]+'_write'](vnfs_ops._hypervisor,
nf_config, buf.rstrip("\n"))
except errors.HypervisorError, ex:
logger.debug('raised OSErro ' + str(ex.errno))
raise OSError(ex.errno, os.strerror(ex.errno))
logger.info('Successfully wrote ' + file_name +
' in ' + nf_config['nf_instance_name'] + '@' + nf_config['host'])
#if buf.rstrip("\n") == "activate":
# try:
# vnfs_ops.vnfs_deploy_nf(nf_path)
# except errors.VNFCreateError:
# #raise OSError(errno.EBUSY, os.strerror(errno.EBUSY))
# raise OSError(747, 'Cannot create VNF')
#elif buf.rstrip("\n") == "stop":
# vnfs_ops.vnfs_stop_vnf(nf_path)
#elif buf.rstrip("\n") == "start":
# vnfs_ops.vnfs_start_vnf(nf_path)
#elif buf.rstrip("\n") == "destroy":
# vnfs_ops.vnfs_destroy_vnf(nf_path)
os.lseek(fh, offset, os.SEEK_SET)
os.write(fh, buf.rstrip("\n"))
return len(buf)
示例6: run_once
def run_once(self):
super(simple_base, self).run_once()
self.loginfo("Starting background docker command, timeout %s seconds", self.config["docker_timeout"])
attach_in_pipe_r, attach_in_pipe_w = os.pipe()
self.sub_stuff["file_desc"].append(attach_in_pipe_r)
self.sub_stuff["file_desc"].append(attach_in_pipe_w)
self.sub_stuff["subargs_a"].append(self.sub_stuff["rand_name"])
dkrcmd = AsyncDockerCmd(self, "attach", self.sub_stuff["subargs_a"], verbose=True)
# Runs in background
self.sub_stuff["cmd_attach"] = dkrcmd
self.sub_stuff["cmdresult_attach"] = dkrcmd.execute(attach_in_pipe_r)
self.wait_interactive_cmd()
self.logdebug("Before input should be ignored: %s", dkrcmd.cmdresult)
# This input should be ignored.
os.write(self.sub_stuff["run_in_pipe_w"], self.config["interactive_cmd_run"] + "\n")
self.logdebug("Before input should be passed: %s", dkrcmd.cmdresult)
# This input should be passed to container.
os.write(attach_in_pipe_w, self.config["interactive_cmd_attach"] + "\n")
self.wait_interactive_cmd()
self.logdebug("After input was passsed: %s", dkrcmd.cmdresult)
示例7: Run
def Run(self, args):
"""Initializes the driver."""
self.SyncTransactionLog()
# This will raise if the signature is bad.
args.driver.Verify(config_lib.CONFIG["Client.driver_signing_public_key"])
if args.force_reload:
try:
self.UninstallDriver(None, args.driver_name, delete_file=False)
except Exception as e: # pylint: disable=broad-except
logging.debug("Error uninstalling driver: %s", e)
path_handle, path_name = tempfile.mkstemp(suffix=".sys")
try:
# TODO(user): Ensure we have lock here, no races
logging.info("Writing driver to %s", path_name)
# Note permissions default to global read, user only write.
try:
os.write(path_handle, args.driver.data)
finally:
os.close(path_handle)
self.InstallDriver(path_name, args.driver_name, args.driver_display_name)
finally:
os.unlink(path_name)
示例8: cosimTimeZero
def cosimTimeZero():
wt = int(os.environ['MYHDL_TO_PIPE'])
rf = int(os.environ['MYHDL_FROM_PIPE'])
buf = "TO 01 "
for s, w in zip(fromSignames, fromSizes):
buf += "%s %s " % (s, w)
os.write(wt, to_bytes(buf))
示例9: cosimToSignalVals
def cosimToSignalVals():
wt = int(os.environ['MYHDL_TO_PIPE'])
rf = int(os.environ['MYHDL_FROM_PIPE'])
buf = "FROM 00 "
for s, w in zip(fromSignames, fromSizes):
buf += "%s %s " % (s, w)
os.write(wt, to_bytes(buf))
os.read(rf, MAXLINE)
buf = "TO 00 "
for s, w in zip(toSignames, toSizes):
buf += "%s %s " % (s, w)
os.write(wt, to_bytes(buf))
os.read(rf, MAXLINE)
os.write(wt, b"START")
os.read(rf, MAXLINE)
buf = "0 "
for s, v in zip(toSignames, toVals):
buf += s
buf += " "
buf += hex(v)[2:]
buf += " "
os.write(wt, to_bytes(buf))
os.read(rf, MAXLINE)
buf = "0 "
for s, v in zip(toSignames, toXVals):
buf += s
buf += " "
buf += v
buf += " "
os.write(wt, to_bytes(buf))
示例10: publish_from_path
def publish_from_path(self, path, content=None):
"""
Gets filename and content for a path, attempts to create directory if
necessary, writes to file.
"""
fn, directory, fngz = self.get_filename_from_path(path)
if not content:
content = self.get_content_from_path(path)
if not os.path.exists(directory):
try:
os.makedirs(directory)
except:
raise StaticGeneratorException('Could not create the directory: %s' % directory)
try:
f, tmpname = tempfile.mkstemp(dir=directory)
os.write(f, content)
os.close(f)
os.chmod(tmpname, stat.S_IREAD | stat.S_IWRITE | stat.S_IWUSR | stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
os.rename(tmpname, fn)
try:
tmpnamegz = '%s.gz' % tmpname
f = gzip.open(tmpnamegz, 'wb')
f.write(content)
f.close()
os.chmod(tmpnamegz, stat.S_IREAD | stat.S_IWRITE | stat.S_IWUSR | stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
os.rename(tmpnamegz, fngz)
except:
raise StaticGeneratorException('Could not create the file: %s' % fngz)
except:
raise StaticGeneratorException('Could not create the file: %s' % fn)
示例11: testContiunePollingOnSubscriberError
def testContiunePollingOnSubscriberError(self):
def cleanUp(_):
w.stop()
def fileDeleted(_):
d = defer.Deferred()
d.addCallback(cleanUp)
reactor.callLater(0, d.callback, _)
return d
def fileChanged(_):
os.remove(tempFile)
raise Exception("This exception shouldn't be raisen")
fd, tempFile = tempfile.mkstemp()
w = watcher.FilesWatcher([tempFile], 0.001)
w.subscribe(fileChanged = fileChanged)
d = defer.Deferred()
d.addCallback(fileDeleted)
w.subscribe(fileDeleted = d.callback)
w.start()
os.write(fd, "test")
os.close(fd)
return d
示例12: _exec
def _exec(self, data):
"""Starts the registered function as a second process
This will fork and start the registered function on a second process.
This shouldn't block on anything. It merely starts then returns.
Args:
data: The data that should be written to stdin on the sub process.
Returns:
Nothing.
"""
logging.warning('Executing process: %s' % self._description)
try:
p = MinimalSubprocess(self._description, data, timeout=self._timeout)
p.fork_exec(self._run_func, self._uid, self._gid)
self._lock.acquire()
self._processes.append(p)
self._lock.release()
if default_ping_fd is not None:
os.write(default_ping_fd, '\0')
except UnknownUserError:
logging.error('%s: Unable to find user %s', self._description,
self._uid)
except UnknownGroupError:
logging.error('%s: Unable to find group %s', self._description,
self._gid)
示例13: set_
def set_(package, question, type, value, *extra):
'''
Set answers to debconf questions for a package.
CLI Example:
.. code-block:: bash
salt '*' debconf.set <package> <question> <type> <value> [<value> ...]
'''
if extra:
value = ' '.join((value,) + tuple(extra))
fd_, fname = salt.utils.mkstemp(prefix="salt-", close_fd=False)
line = "{0} {1} {2} {3}".format(package, question, type, value)
os.write(fd_, line)
os.close(fd_)
_set_file(fname)
os.unlink(fname)
return True
示例14: do_edit
def do_edit(given_cl, current_cl, cl_file_path):
if given_cl.is_unspecified():
# Show an editor if CL not specified on the command-line
tmp_fd, tmp_path = tempfile.mkstemp(prefix='appspot-', suffix='.txt')
os.write(tmp_fd, editable_change(current_cl))
os.close(tmp_fd)
retcode = subprocess.call(
'%s %s' % (os.getenv('VISUAL', os.getenv('EDITOR', 'vi')),
commands.mkarg(tmp_path)),
shell=True)
try:
if retcode < 0:
raise Exception('editor closed with signal %s' % -retcode)
elif retcode > 0:
raise Exception('editor exited with error value %s' % retcode)
edited_cl = parse_change(open(tmp_path).read())
finally:
os.remove(tmp_path)
if edited_cl.is_unspecified():
print >>sys.stderr, 'cancelled edit'
return
edited_cl.merge_into(current_cl)
else:
given_cl.merge_into(current_cl)
out = open(cl_file_path, 'w')
out.write(editable_change(current_cl))
out.close()
示例15: rlogout
def rlogout(tty, timeout=TIMEOUT):
"""
End remote session.
"""
os.write(tty, "exit" + os.linesep);
expect(tty, ["closed."], timeout=timeout);