V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
SimbaPeng
V2EX  ›  Python

使用 vscode 运行 Python 的问题。

  •  
  •   SimbaPeng · 2017-11-13 04:00:00 +08:00 · 3740 次点击
    这是一个创建于 2362 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import os

    print('Process ({}) start...'.format(os.getpid()))

    # 创建子进程
    pid = os.fork()

    使用 vscode 运行这段代码,居然会输出 2 次 Process ... start ... 。 用终端调用就没问题,只输出一次。



    import time

    print(1)
    time.sleep(5)

    然后运行这段代码的时候,会等到 5 秒之后才输出 1.


    import sys

    import time

    print(1)
    sys.stdout.flush()
    time.sleep(5)

    必须加上 sys.stdout.flush() 这个才会马上输出。。。


    我用的是 macbook pro

    vscode 的 task.json 是这样的:

    {
    "version": "0.1.0",
    "command": "${config:python.pythonPath}",
    "type": "shell",
    "args": ["${file}"]
    }

    使用 sublime 和 PyCharm 运行 python 脚本就没这 2 个问题
    10 条回复    2017-11-13 11:38:09 +08:00
    rogwan
        1
    rogwan  
       2017-11-13 07:20:06 +08:00 via Android
    vscode 的哪个版本?
    SimbaPeng
        2
    SimbaPeng  
    OP
       2017-11-13 09:31:33 +08:00
    @rogwan 1.18.0
    rogwan
        3
    rogwan  
       2017-11-13 09:44:50 +08:00 via Android
    最新版还没试过,有空去下个测试下,IDE 多多少少都有提示不准确的情况,这种运算逻辑的问题太严重了
    debuggerx
        4
    debuggerx  
       2017-11-13 09:59:35 +08:00 via Android
    延迟那个是不是因为 python 的输出缓冲?试试在 command 里加上-u 参数?并不用 vsc,感觉它调用 shell 的方式很难用……
    clino
        5
    clino  
       2017-11-13 10:08:22 +08:00
    第一个我试过了只打一次啊
    第二个应该就是 stdio 的缓冲,方法就是 4 楼的加参数了
    onlyice
        6
    onlyice  
       2017-11-13 10:23:45 +08:00   ❤️ 1
    正常,print 打到 stdout 是块缓冲的,缓冲区在 fork 时一起给到子进程

    你需要 sys.stderr.write
    SimbaPeng
        7
    SimbaPeng  
    OP
       2017-11-13 10:57:21 +08:00
    @onlyice 哦哦,那为什么直接使用终端 print 没有缓冲呢?
    onlyice
        8
    onlyice  
       2017-11-13 11:02:56 +08:00
    @SimbaPeng 大概是你的终端做了什么手脚。。
    SimbaPeng
        9
    SimbaPeng  
    OP
       2017-11-13 11:26:28 +08:00
    @onlyice 我看了下文档明白了,输出到控制台的时候是使用的行缓冲
    zhusimaji
        10
    zhusimaji  
       2017-11-13 11:38:09 +08:00
    实测没有楼主的问题
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2240 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 07:57 · PVG 15:57 · LAX 00:57 · JFK 03:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.