网络知识 百科 python代码没错但运行不出来(python无法运行代码)

python代码没错但运行不出来(python无法运行代码)

python代码没错但运行不出来, Python代码没错,但是为什么运行不了?不知道小伙伴们今天来看看边肖的分享吧!

1.python代码正确却无法运行的原因:

在项目中,python脚本用于不断将日志文件中的数据转换为另一个文件,以供其他日志分析应用程序使用。但是当后台操作重定向到一个文件时,发现没有内容输出。该命令如下所示:

python xxx.py xxx.log

测试显示,直接输出到终端时前台正常,后台运行重定向输出到文件时无法输出。

python无法运行代码

2.解决方案:

发现程序运行时输出是缓存的,只有程序运行或缓冲区满了才会输出。因为程序一直在运行,所以不可能等程序结束再输出。而且要求是实时的,不建议等缓冲区满了再输出。

所以在python运行时添加-u参数,比如:

python -u xxx.py xxx.log

-u参数的意思是输入和输出不需要缓冲。

详情如下:

Forces stdin, stdout and stderr to be completely unbuffered. On important systems, stdin, stdout and stderr are also put into binary mode. Note that there is an internal buffer in xreadlines (), readlines () and file object iterator (for lines in sys.stdin), which is not affected by this option. To solve this problem, you need to use sys.stdin.readline () in the while 1: "loop.

补充知识:用python运行代码没有错误,但是没有输出,有退出代码0的结束标志。

如下所示:

f=open(passwd.txt,r)

print (f.read(4))

f.close()

这是您想要执行的代码

passwd.txt中的内容

ntp:x:38:38:/etc/ntp:/sbin/nologin

apache:x:48:48:Apache:/var/www:/sbin/nologin

saslauth:x:498:76:Saslauthd user:/var/empty/saslauth:/sbin/nologin

postfix:x:89:89:/var/spool/postfix:/sbin/nologin

gdm:x:42:42:/var/lib/gdm:/sbin/nologin

pulse:x:497:496:PulseAudio System Daemon:/var/run/pulse:/sbin/nologin

但是输出的结果是

Process finished with exit code 0

后来调查发现是翻译的问题。

我之前用的解释器是pycharm提供的虚拟解释器。

# # # #如何查看解释器

Point files? Cnew project

python无法运行代码

如果选择2,则使用pycharm提供的虚拟解释器,因为passwd.txt文件不在虚拟环境中,所以没有输出。

点击3并选择您下载的解释器。

python代码没错但运行不出来,以上就是本文为您收集整理的python代码没错但运行不出来最新内容,希望能帮到您!更多相关内容欢迎关注。

本文来自网络,不代表本站立场,转载请注明出处:https://www.tlcement.com/a/90605.html

python代码没错但运行不出来

网络知识后续将为您提供丰富、全面的关于python代码没错但运行不出来内容,让您第一时间了解到关于python代码没错但运行不出来的热门信息。小编将持续从百度新闻、搜狗百科、微博热搜、知乎热门问答以及部分合作站点渠道收集和补充完善信息。