GVKun编程网logo

python print()(pythonprint用法)

1

这篇文章主要围绕pythonprint和展开,旨在为您提供一份详细的参考资料。我们将全面介绍pythonprint的优缺点,解答的相关问题,同时也会为您带来10.Python中print函数中中逗号和

这篇文章主要围绕python print展开,旨在为您提供一份详细的参考资料。我们将全面介绍python print的优缺点,解答的相关问题,同时也会为您带来10.Python 中 print 函数中中逗号和加号的区别、DeBug Python 代码全靠 print 函数?换用这个一天 2K+Star 的工具吧,改进版、gyp ERR! stack Error: Command failed: E:\python.EXE -c import sys; print "%s.%s.%s" % sys.version_、IDEA 当前在线人数和历史访问量的示例代码当前在线人数:${count}"); out.print("您是第 "+ servletContext.getAttribute("count")+"位访客"); out.print("

"); out.print(" " + ""); } /** * @see HttpServlet#doPost(HttpServ的实用方法。

本文目录一览:

python print()(pythonprint用法)

python print()(pythonprint用法)

print([object, ...][, sep='' ''][, end=''\n''][, file=sys.stdout])

Print object(s) to the stream file, separated by sep and followed by endsepend and file, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep andend must be strings; they can also be None, which means to use the default values. If no object is given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or Nonesys.stdout will be used. Output buffering is determined byfile. Use file.flush() to ensure, for instance, immediate appearance on a screen.

Note

 

This function is not normally available as a built-in since the name print is recognized as the print statement. To disable the statement and use the print() function, use this future statement at the top of your module:

10.Python 中 print 函数中中逗号和加号的区别

10.Python 中 print 函数中中逗号和加号的区别

先看看 print 中逗号和加号分别打印出来的效果..

这里以 Python3 为例

1
print("hello" + "world")
helloworld
1
print("hello", "world")
hello world

这里发现加号的作用是连接字符串 而逗号相当于用空格连接字符串。

尝试一下不同数据类型的操作..

1
print("hello" + 123)
TypeError: must be str, not int
1
print("hello", 123)
hello 123

这里发现加号在 Str 类型与 Num 类型相加的出现了类型错误 逗号连接正常并返回字符串结果。

总结:

加号 + :两边只能是相同数据类型,在 Python 中主要是运算符的存在,而字符串等类型相加只是 Python 中的内置方法。

逗号,: 在这里逗号更多的代表用空格的连接。

DeBug Python 代码全靠 print 函数?换用这个一天 2K+Star 的工具吧,改进版

DeBug Python 代码全靠 print 函数?换用这个一天 2K+Star 的工具吧,改进版

 

pysnooper是代码debug神器,比无限low print好很多和也比日志debug好一些,比断点调试也好一些,这个很犀利的装饰器。

https://www.toutiao.com/a6682957535856558606/
DeBug Python代码全靠print函数?换用这个一天2K+Star的工具吧

对其修改了2点。
1、由于部署一般是linux,开发是windows,所以可以禁止linux上使用调试,相同的代码在linux上运行,调试装饰器自动失效,因为忘了注释掉装饰器,在生产调试会消耗性能。
2、将代码运行轨迹修改成可以点击的,点击控制台的行号即可跳转到pycharm对应的代码行。
3、提供一个猴子补丁,使用猴子补丁修改三方包的模块级全局变量MAX_VARIABLE_LENGTH ,最大变量默认是100,但对调试对接方json时候,往往很大,可以加大到最大显示10万个字母。

 
# -*- coding: utf-8 -*-
# @Author  : ydf
import datetime
import os
from functools import wraps
import decorator
import pysnooper  # 需要安装 pip install pysnooper==0.0.11
from pysnooper.pysnooper import get_write_function
from pysnooper.tracer import Tracer, get_local_reprs, get_source_from_frame

os_name = os.name


class TracerCanClick(Tracer):
    """
    使运行轨迹可点击。
    """

    def trace(self, frame, event, arg):
        if frame.f_code is not self.target_code_object:
            if self.depth == 1:

                return self.trace
            else:
                _frame_candidate = frame
                for i in range(1, self.depth):
                    _frame_candidate = _frame_candidate.f_back
                    if _frame_candidate is None:
                        return self.trace
                    elif _frame_candidate.f_code is self.target_code_object:
                        indent = '' '' * 4 * i
                        break
                else:
                    return self.trace
        else:
            indent = ''''

        self.frame_to_old_local_reprs[frame] = old_local_reprs = \
            self.frame_to_local_reprs[frame]
        self.frame_to_local_reprs[frame] = local_reprs = \
            get_local_reprs(frame, variables=self.variables)

        modified_local_reprs = {}
        newish_local_reprs = {}

        for key, value in local_reprs.items():
            if key not in old_local_reprs:
                newish_local_reprs[key] = value
            elif old_local_reprs[key] != value:
                modified_local_reprs[key] = value

        newish_string = (''Starting var:.. '' if event == ''call'' else
                         ''New var:....... '')
        for name, value_repr in newish_local_reprs.items():
            self.write(''{indent}{newish_string}{name} = {value_repr}''.format(
                **locals()))
        for name, value_repr in modified_local_reprs.items():
            self.write(''{indent}Modified var:.. {name} = {value_repr}''.format(
                **locals()))

        now_string = datetime.datetime.now().time().isoformat()
        source_line = get_source_from_frame(frame)[frame.f_lineno - 1]
        # print(frame)
        # print(dir(frame.f_code))
        # print(frame.f_code.co_filename)
        file_name_and_line = f''{frame.f_code.co_filename}:{frame.f_lineno}''
        # print(file_name_and_line)

        # self.write(''{indent}{now_string} {event:9} ''
        #            ''{frame.f_lineno:4} {source_line}''.format(**locals()))
        file_name_and_line2 = f''"{file_name_and_line}"''
        self.write(''{indent}{now_string} {event:9} ''  # REMIND 主要是修改了这一行,使debug可点击。
                   ''{file_name_and_line2:100} {source_line}''.format(**locals()))
        return self.trace


def _snoop_can_click(output=None, variables=(), depth=1, prefix=''''):
    write = get_write_function(output)

    # noinspection PyShadowingBuiltins
    @decorator.decorator
    def decorate(function, *args, **kwargs):
        target_code_object = function.__code__
        with TracerCanClick(target_code_object=target_code_object,
                            write=write, variables=variables,
                            depth=depth, prefix=prefix):
            return function(*args, **kwargs)

    return decorate


def snoop_deco(output=None, variables: tuple = (), depth=1, prefix='''', do_not_effect_on_linux=True, line_can_click=True):
    # REMIND 对装饰器再包装一次,不使用上面的和官方的。
    def _snoop(func):
        nonlocal prefix
        if prefix == '''':
            prefix = f''调试 [{func.__name__}] 函数 -->  ''

        @wraps(func)
        def __snoop(*args, **kwargs):
            if os_name == ''posix'' and do_not_effect_on_linux:  # 不在linux上debug
                return func(*args, **kwargs)
            else:
                if line_can_click:
                    return _snoop_can_click(output, variables, depth, prefix)(func)(*args, **kwargs)
                else:
                    return pysnooper.snoop(output, variables, depth, prefix)(func)(*args, **kwargs)

        return __snoop

    return _snoop


def patch_snooper_max_variable_length(max_lenth=100000):
    """
    提供一个猴子补丁,三方包默认是变量最大显示100个字母,对于我这种经常debug对接方json的,要加到10万才能显示一个josn。
    最好是放在__name__ == main中去执行此补丁,否则由于模块是单例的永远只导入一次,如果本文件被其他地方导入,也会改变当前python解释器的其他也使用snooper地方的运行表现也加到10万了。
    :param max_lenth:
    :return:
    """
    from pysnooper import tracer
    tracer.MAX_VARIABLE_LENGTH = max_lenth


if __name__ == ''__main__'':
    @snoop_deco(line_can_click=True)
    def fun2():
        x = 1
        x += 2


    fun2()

 

 

 

原版是上面这样,不能点击,修改后,直接点击链接可以跳转到代码对应地方。不用加很多 print 来确定代码运行了什么分支。

 

gyp ERR! stack Error: Command failed: E:\python.EXE -c import sys; print

gyp ERR! stack Error: Command failed: E:\python.EXE -c import sys; print "%s.%s.%s" % sys.version_

vue项目执行npm install 出现异常:

gyp ERR! stack Error: Command failed: E:\python.EXE -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                                ^
gyp ERR! stack SyntaxError: invalid syntax
gyp ERR! stack
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:308:12)
gyp ERR! stack     at ChildProcess.emit (events.js:315:20)
gyp ERR! stack     at maybeClose (internal/child_process.js:1048:16)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:288:5)
gyp ERR! System Windows_NT 10.0.19043
gyp ERR! command "E:\\install\\nodejs\\node.exe" "F:\\xxx\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="

解决方法:

  1. npm config set python E:\Python27
  2. 修改全局环境path的python安装路径

"); out.print(" " + ""); } /** * @see HttpServlet#doPost(HttpServ" alt="IDEA 当前在线人数和历史访问量的示例代码当前在线人数:${count}"); out.print("您是第 "+ servletContext.getAttribute("count")+"位访客"); out.print("

"); out.print(" " + ""); } /** * @see HttpServlet#doPost(HttpServ">

"); out.print(" " + ""); } /** * @see HttpServlet#doPost(HttpServ">IDEA 当前在线人数和历史访问量的示例代码当前在线人数:${count}"); out.print("您是第 "+ servletContext.getAttribute("count")+"位访客"); out.print("

"); out.print(" " + ""); } /** * @see HttpServlet#doPost(HttpServ

这篇文章主要介绍了IDEA 当前在线人数和历史访问量的实例代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

当前在线人数

一共需要三处

创建监听器

package com.count; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.servletcontextlistener; import javax.servlet.annotation.WebListener; /* 初始化: 只有服务器的启动,才会创建servletContext对象。 用于监听servletContext创建,一旦创建servletContext创建,则设置servletContext中的count值为0; */ @WebListener /* 这个注解的作用是启动监听,相当于在web.xml配置( com.cyl.count.InitServletContexListener */ public class InitServletContexListener implements servletcontextlistener { @Override public void contextinitialized(ServletContextEvent servletContextEvent) { //获取ServletContext域对象 ServletContext servletContext = servletContextEvent.getServletContext(); //给ServletContext域对象,设置count=0 servletContext.setAttribute("count",0); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { } }

package com.count; import javax.servlet.ServletContext; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; /** * @监听在线人数,监听session的创建和销毁 * 如果session创建 获取ServletContext中的count++,重新设置 * 如果session销毁 获取ServletContext中的count--,重新设置 */ @WebListener public class OnlineNumberHttpSessionListener implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent httpSessionEvent) { //1.获取session HttpSession session = httpSessionEvent.getSession(); ServletContext servletContext = session.getServletContext(); //2.获取counnt值,加1 int count = (int) servletContext.getAttribute("count"); count++; //3.把servlet存储到servletContext对象中 servletContext.setAttribute("count",count); } @Override public void sessionDestroyed(HttpSessionEvent httpSessionEvent) { //1.获取session HttpSession session = httpSessionEvent.getSession(); ServletContext servletContext = session.getServletContext(); //2.获取counnt值,减1 int count = (int) servletContext.getAttribute("count"); count++; //3.把servlet存储到servletContext对象中 servletContext.setAttribute("count",count); } }

修改index.jsp

$Title$

当前在线人数:${count}

历史访问量

import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletContext; import javax.servlet.servletexception; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class countServlet1 */ @WebServlet("/countServlet1") public class countServlet1 extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public countServlet1() { super(); // Todo Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws servletexception, IOException { //设置字符编码 request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; charset=utf-8"); //获取全局的共享数据 ServletContext servletContext = this.getServletContext(); //获取计数器count Integer count = (Integer) servletContext.getAttribute("count"); //如果获取的计算器对象为空 ,说明是第一次访问,并将count,放入servletCount if( servletContext.getAttribute("count") == null) { count = 1; servletContext.setAttribute("count", count); }else { //否则就不是第一次访问,将登陆的计数器进行加1的数据更新 servletContext.setAttribute("count", count+1); } //将登陆的次数显示在页面上 PrintWriter out =response.getWriter(); out.print("rn" + "rn" + "rn" + "rn" + "登陆网页次数统计rn" + "rn" + ""); out.print("

"); out.print("您是第 "+ servletContext.getAttribute("count")+"位访客"); out.print(""); out.print("rn" + ""); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws servletexception, IOException { // Todo Auto-generated method stub doGet(request, response); } }

$Title$

欢迎您访问,本页面已经被访问过 次

总结

到此这篇关于IDEA :当前在线人数和历史访问量的文章就介绍到这了,更多相关IDEA :当前在线人数和历史访问量内容请搜索小编以前的文章或继续浏览下面的相关文章希望大家以后多多支持小编!

关于python print的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于10.Python 中 print 函数中中逗号和加号的区别、DeBug Python 代码全靠 print 函数?换用这个一天 2K+Star 的工具吧,改进版、gyp ERR! stack Error: Command failed: E:\python.EXE -c import sys; print "%s.%s.%s" % sys.version_、IDEA 当前在线人数和历史访问量的示例代码当前在线人数:${count}"); out.print("您是第 "+ servletContext.getAttribute("count")+"位访客"); out.print("

"); out.print(" " + ""); } /** * @see HttpServlet#doPost(HttpServ的相关信息,请在本站寻找。

本文标签: