• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python sys.stdout函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sys.stdout函数的典型用法代码示例。如果您正苦于以下问题:Python stdout函数的具体用法?Python stdout怎么用?Python stdout使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了stdout函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: get_events

def get_events(f5,f5type="minknow",metrichor=None):
    if f5type == "metrichor":
        path = "Analyses/EventDetection_000/Reads/Read_0/Events"
    elif f5type == "minknow":
        path = "Analyses/EventDetection_000/Reads/Read_0/Events"
    for event in f5[path]:
        sys.stdout(event+"\n")
开发者ID:JohnUrban,项目名称:poreminion,代码行数:7,代码来源:hdf_fxns.py


示例2: get_num_events

def get_num_events(f5,f5type="minknow"):
    if f5type == "metrichor":
        path = "Analyses/EventDetection_000/Reads/Read_0/Events"
    elif f5type == "minknow":
        path = "Analyses/EventDetection_000/Reads/Read_0/Events"
##    for event in f5[path]:
##        sys.stdout(event+"\n")
    sys.stdout(f5[path].len()+"\n")
开发者ID:JohnUrban,项目名称:poreminion,代码行数:8,代码来源:hdf_fxns.py


示例3: write

 def write(self, output):
     if SYSLOG:
         if output == "\n": return
         syslog(output)
     elif self.logfile:
         self.logfile.write(output)
     else:
         sys.stdout(output)
         sys.stdout.flush()
开发者ID:mathstuf,项目名称:yokadi,代码行数:9,代码来源:daemonutils.py


示例4: handle

    def handle(self, *args, **options):

        try:
            git_cmd = sh.git.bake('--no-pager')
            WILHELM_VERSION\
                = git_cmd(['log', '--pretty=format:%H']).stdout.strip().split('\n')[0]

            with open(version_filename, 'w') as f:
                f.write(WILHELM_VERSION)

        except:
            sys.stdout('Could not write wilhelm version to file.')
开发者ID:lawsofthought,项目名称:wilhelmproject,代码行数:12,代码来源:set_wilhelm_version.py


示例5: update_token

 def update_token(self, social_app, social_token):
     request_url = 'https://graph.facebook.com/oauth/access_token?client_id=%s&client_secret=%s&grant_type=fb_exchange_token&fb_exchange_token=%s' % (
         social_app.key, social_app.secret, social_token.token)
     try:
         response = urlparse.parse_qs(urllib2.urlopen(request_url).read())
         new_token = response.get('access_token', [None])[0]
         timeleft = response.get('expires', [0])[0]
         if new_token and timeleft:
             expiry_date = datetime.datetime.now() + datetime.timedelta(seconds=int(timeleft)+60)
             social_token.token = new_token
             social_token.save(expiry_date=expiry_date, updated=True)
             
     except urllib2.HTTPError, e:
         sys.stdout('Request URL:\n%s\n\nError:\n%s' % (request_url, e.read() or 'Unknown error'))
开发者ID:artminster,项目名称:django-allauth,代码行数:14,代码来源:provider.py


示例6: reload_services

def reload_services():
    """This function reloads configurations of PHP-FPM and NGINX services"""
    res = subprocess.run([
        '/etc/init.d/php7.0-fpm',
        'reload'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if res.stderr != b'':
        sys.stdout('Unable to reload PHP: %s\n' % res.stderr)
        sys.exit(1)
    res = subprocess.run([
        '/usr/sbin/nginx',
        '-s',
        'reload'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if res.stderr != b'':
        sys.stdout('Unable to reload NGINX: %s\n' % res.stderr)
        sys.exit(1)
开发者ID:matteomattei,项目名称:servermaintenance,代码行数:15,代码来源:lemp_manager.py


示例7: getconn

def getconn(dbfile):
    # we force the directory to be db_dir()
    dbpath = db_path(dbfile)

    if not os.path.exists(dbpath):
        print "dbfile '" + dbfile + "' does not exist"
        sys.exit(45)

    try:
        conn = sqlite.connect(dbpath)
        conn.row_factory = sqlite.Row
        conn.create_function("regexp", 2, regexp)
    except:
        sys.stdout('Could not connect to dbfile: "%s"<br>' % dbfile)
        sys.exit(45)

    return conn
开发者ID:esheldon,项目名称:misc,代码行数:17,代码来源:recipe_util.py


示例8: init_log

def init_log(log_dir=None):
    if log_dir and not path.exists(log_dir):
        msg = '指定路径不存在:%s' % log_dir
        sys.stdout(msg)
        log_dir = None

    config = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'default': {
                'format': '%(levelname)s %(asctime)s %(module)s:%(funcName)s:%(lineno)d %(message)s'
            },
            'simple': {
                'format': '%(level)s %(message)s'
            }
        },
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
                'formatter': 'default',
            },
        },
        'loggers': {
            '': {
                'handlers': ['console'],
                'level': 'INFO',
                'propagate': True,
            },
        }
    }

    if log_dir:
        config['handles']['file'] = {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': path.join(log_dir, 'essay.log'),
            'maxBytes': 1024 * 1024 * 50,
            'backupCount': 5,
            'formatter': 'default',
        }
        config['loggers']['handlers'] = ['console', 'file']

    logging.config.dictConfig(config)
开发者ID:SohuTech,项目名称:essay,代码行数:45,代码来源:log.py


示例9: main

def main():
    gui_sock = create_socket((HOST_GUI, PORT_GUI))
    idp = gui_sock.recv(1024)

    if idp != "MyMainServer":
        sys.stdout("Try again with MyMainServer")
        sys.exit(1)

    idp_sock = create_socket((HOST_MAIN, PORT_MAIN))
    main_id = idp_sock.recv(1024)
    main_id = int(main_id)
    #main_id = 11

    user_info = get_user_info(main_id)
    gui_sock.send(user_info)

    gui_sock.close()
    idp_sock.close()
开发者ID:ELLE209,项目名称:MyProject,代码行数:18,代码来源:MySP.py


示例10: ioHandler

    def ioHandler(self, records = None):

        self.records = records

        if not os.path.exists(self.record):
            with open(self.record, "w") as f:
                cPickle.dump([], f)
        if self.action == "w":
            with open(self.record, "w") as f:
                cPickle.dump(records, f)
            return True
        elif self.action == "r":
            with open(self.record) as f:
                records_old = cPickle.load(f)
            return records_old
        elif self.action == "s":
            # Nothing will happen in this method.
            sys.stdout("If you want to search something, pls use FakeDB.search().")
        else:
            raise ValueError("No such DB operation.")
开发者ID:kangyanlin,项目名称:ultrastorage,代码行数:20,代码来源:fakedb.py


示例11: dump_metrics

def dump_metrics(dump_file, experiment_file, start_time, elapsed_time,
                 backend_name, metrics, field_sep="\t"):
    """
    Write or append collected metric values to the specified flat file.

    Arguments:
        dump_file (str): path to file to write. Will be created if doesn't
                         exist, or appended to (without header if it does)
        experiment_file (str): path to yaml file used to run this experiment
        start_time (str): date and time at which experiment was started.
        elapsed_time (float): time taken to run the experiment.
        metrics (dict): Collection of metric values, as returned from
                        FitPredictErrorExperiment.run() call.
        field_sep (str, optional): string used to separate each field in
                                   dump_file.  Defaults to tab character.
    """
    if dump_file is None or dump_file == '':
        df = sys.stdout()
    elif not os.path.exists(dump_file) or os.path.getsize(dump_file) == 0:
        ensure_dirs_exist(dump_file)
        df = open(dump_file, 'w')
        metric_names = []
        if isinstance(metrics, dict):
            metric_names = ["%s-%s" % (metric.lower(), dset.lower())
                            for metric in sorted(metrics.keys())
                            for dset in sorted(metrics[metric].keys())]
        df.write(field_sep.join(["host", "architecture", "os",
                                 "os_kernel_release", "neon_version",
                                 "backend",
                                 "yaml_name", "yaml_sha1", "start_time",
                                 "elapsed_time"] + metric_names) + "\n")
    else:
        df = open(dump_file, 'a')
    info = os.uname()
    trunc_exp_name = ("..." + os.path.sep +
                      os.path.dirname(experiment_file).split(os.path.sep)[-1] +
                      os.path.sep +
                      os.path.basename(experiment_file))
    # TODO: better handle situation where metrics recorded differ from those
    # already in file
    metric_vals = []
    if isinstance(metrics, dict):
        metric_vals = ["%.5f" % metrics[metric][dset] for metric in
                       sorted(metrics.keys()) for dset in
                       sorted(metrics[metric].keys())]
    df.write(field_sep.join([x.replace("\t", " ") for x in
                             [info[1], info[4], info[0], info[2],
                              neon.__version__, backend_name, trunc_exp_name,
                              hashlib.sha1(open(experiment_file,
                                                'rb').read()).hexdigest(),
                              start_time, "%.3f" % elapsed_time] +
                             metric_vals]) + "\n")
    df.close()
开发者ID:JesseLivezey,项目名称:neon,代码行数:53,代码来源:metric.py


示例12: decode_folder

def decode_folder(session,source,level,folder):
    global g_cnt
    try:
        xml = lxml.etree.fromstring(source)
    except:
        sys.stdout('#')
        sys.stdout.flush()
        print source  
    nsmap = {'atom': 'http://www.w3.org/2005/Atom','d': 'http://schemas.microsoft.com/ado/2007/08/dataservices','m': 'http://schemas.microsoft.com/ado/2007/08/dataservices/metadata'}
    cnt=0
    for m in xml.xpath("//atom:entry/atom:content/m:properties", namespaces=nsmap):
		cnt = cnt + 1
		g_cnt = g_cnt + 1
		N = m.find('d:Name', namespaces=nsmap)
		L = m.find('d:ServerRelativeUrl', namespaces=nsmap)
		I = m.find('d:ItemCount', namespaces=nsmap)
		U = m.find('d:UniqueId', namespaces=nsmap)
		rep = urllib.quote(L.text.encode('windows-1252'))
		ligne = 'd;'+urllib.unquote(folder.encode("windows-1252"))+';"'+N.text.encode('windows-1252')+'";"'+args.site+rep+'";'+I.text+';'+U.text+';'+rep+'\n'
		fo.write(ligne)
		recurse_dir(session,rep,level)
    return
开发者ID:e-coucou,项目名称:sharepoint,代码行数:22,代码来源:liste_sharepoint.py


示例13: main

def main():

    global THINGSPEAKKEY
    global THINGSPEAKURL
    global CFGFILE
    global TEMPOUT
    global AIRPRESSURE

    try:

        while True:
            readDataERIK()
            sendDataERIK(THINGSPEAKURL, THINGSPEAKKEY, "field1", "field2", TEMPOUT, AIRPRESSURE)
            sys.stdout.flush()

            # Toggle LED while we wait for next reading
            for i in range(0, INTERVAL * 60):
                time.sleep(1)

    except:
        # Reset GPIO settings
        # GPIO.cleanup()
        sys.stdout("exception!")
开发者ID:Philur,项目名称:templogger,代码行数:23,代码来源:SimpleReadFile.py


示例14: len

                         index = s
                         a = in_hand.pop(s)
                         break
                 else:
                     a = in_hand.pop(0)
                     b = []
                     break
                     
         sys.stdout.write("%d %d\n" % (a, len(b)))
         for i in xrange(len(b)):
             sys.stdout.write("%d " % (b[i]))
         sys.stdout.write("\n")
     else:
         a = in_hand.pop(0)
         b = 0
         sys.stdout("%d %d\n" % (a, b))
 else:
     index = 0
     while True:
         a = in_hand.pop(index)
         in_table.append(a)
         in_table.sort()
         b = closestSum(in_table, a)
         if sum(b) >= a:
             in_hand.insert(index, a)
             for s in xrange(index, len(in_hand)+1):
                 if in_hand[s] > sum(b):
                     index = s
                     a = in_hand.pop(s)
                     break
             else:
开发者ID:indradhanush,项目名称:Algorithms,代码行数:31,代码来源:pennywise.py


示例15: len

import os
import shutil
import sys
import argparse
import uuid
import fnmatch

parser = argparse.ArgumentParser()

parser.add_argument("--dir", help="Source Path")

args = parser.parse_args()

tilefiles = []

for root, dirs, files in os.walk(args.dir):
     for name in fnmatch.filter(files, "*title*"):
        tilefiles.append(os.path.join(root, name))

if len(tilefiles) == 0:
    sys.stdout("Error no title file!")

for titlefile_path in tilefiles:

    unsortedfile = os.path.join(os.path.dirname(titlefile_path),str(uuid.uuid1())+".pdf")
  
    try:
        shutil.move(titlefile_path, unsortedfile)
    except:
        print("can not move file %s -> %s" % (titlefile_path, unsortedfile))
开发者ID:afeldman,项目名称:sortpdf,代码行数:30,代码来源:renameWITHuuid.py


示例16: stdoutMP

def stdoutMP(lock, msg):
    import sys
    lock.acquire()
    sys.stdout(msg)
    lock.release()
开发者ID:RoyLab,项目名称:HairTraining,代码行数:5,代码来源:common_tools.py


示例17: outFunction

 def outFunction(*args, **kwargs):
     sys.stdout('Arguments:\n'+str(args))
     sys.stdout('Arguments with keyword:\n'+str(kwargs))
     pass
开发者ID:hacklabcz,项目名称:pearl,代码行数:4,代码来源:misc.py


示例18: example18


# @example
# def example18():
#     widgets = [Percentage(),
#                ' ', Bar(),
#                ' ', ETA(),
#                ' ', AdaptiveETA()]
#     pbar = ProgressBar(widgets=widgets, maxval=500)
#     pbar.start()
#     for i in range(500):
#         time.sleep(0.01 + (i < 100) * 0.01 + (i > 400) * 0.9)
#         pbar.update(i + 1)
#     pbar.finish()


@example
def example19():
    pbar = ProgressBar()
    for i in pbar([]):
        pass
    pbar.finish()


if __name__ == "__main__":
    try:
        for example in examples:
            example()
    except KeyboardInterrupt:
        sys.stdout("\nQuitting examples.\n")
开发者ID:pigletfly,项目名称:checkio,代码行数:28,代码来源:test_progressbar.py


示例19: variable

# I added these functions to make it easier to print with different colors
# The are shorthand for the write, printf, and make functions above
# e.g. colortext.pcyan('test') prints in cyan, colortext.wlightpurple('test') writes in light purple, colortext.mblue('test') returns a blue string
# Note: Python does not close the scope in for-loops so the closure definition looks odd - we need to explicitly capture the state of the c variable ("c=c")
# Note: we should handle kwargs here in the future
def xprint(*args): print(args)
def xjoin(*args): return ''.join(map(str, args))
for c in colors:
    allow_colors = False
    try:
        from sys import platform as _platform
        if _platform == "linux" or _platform == "linux2" or _platform == "darwin":
            allow_colors = True
    except: pass
    if allow_colors:
        setattr(sys.modules[__name__], 'w'  + c, lambda s, c=c : write(s, color = c))
        setattr(sys.modules[__name__], 'p'  + c, lambda s, c=c : printf(s, color = c))
        setattr(sys.modules[__name__], 'm'  + c, lambda s, c=c : make(s, color = c))
    else:
        setattr(sys.modules[__name__], 'w'  + c, lambda s, c=c : sys.stdout(s))
        setattr(sys.modules[__name__], 'p'  + c, lambda s, c=c : xprint(s))
        setattr(sys.modules[__name__], 'm'  + c, lambda s, c=c : xjoin(s))


class Exception(Exception):
    def __init__(self, msg):
        self.message = make_error(msg)
    def __str__(self):
        return self.message
开发者ID:Aviouz,项目名称:loop_modeling,代码行数:29,代码来源:colortext.py


示例20: make_server

    return [stdout.getvalue()]


def make_server(
    host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler
):
    """Create a new WSGI server listening on `host` and `port` for `app`"""
    server = server_class((host, port), handler_class)
    server.set_app(app)
    return server


if __name__ == '__main__':
    httpd = make_server('', 8000, demo_app)
    sa = httpd.socket.getsockname()
    sys.stdout("Serving HTTP on %s port %s...\n" % (sa[0], sa[1]))
    import webbrowser
    webbrowser.open('http://localhost:8000/xyz?abc')
    httpd.handle_request()  # serve one request, then exit











开发者ID:AishwaryaKM,项目名称:python-tutorial,代码行数:19,代码来源:simple_server.py



注:本文中的sys.stdout函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python sys.sys_exit函数代码示例发布时间:2022-05-27
下一篇:
Python sys.stderr函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap