python代码没错但运行不出来
python代码没错但运行不出来是什么原因呢?不知道的小伙伴来看看小编今天的分享吧!
1、python代码没错但运行不出来的原因:
某项目中使用python脚本方式将日志文件中的数据持续的转换格式输出到另一文件中以供其他日志分析应用使用。但是当后台运行采取重定向方式输出到某一文件时,发现并没有内容输出,命令如下:
python xxx.py > xxx.log &
测试发现,当前台直接输出到终端时正常,使用后台运行重定向的方式输出到文件中时无法输出。
2、解决办法:
发现是在程序运行时,输出有缓存,只有当程序运行结束或者缓冲区满后才会输出。因为程序是一致在运行的所以不可能等待程序结束在输出。并且要求是有实时性的所以等缓冲区满输出的方式也不可取。
所以采用在python运行时加上-u参数,如:
python -u xxx.py > xxx.log &
-u参数的意义是不使用缓冲的方式输入输出
详细如下:
Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xreadlines(), readlines() and file-object iterators ("for line in sys.stdin”) which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()” inside a "while 1:” loop.
补充知识:python中运行代码时没有报错但是也没有输出而且还有exit code 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提供的虚拟解释器
#####如何查看解释器
点file?C>new projects
如果选择的是2就是使用了pycharm提供的虚拟解释器,又因为passwd.txt文件不是在虚拟环境中的所以就没有输出。
点击3然后选择你已经下载好的解释器即可。
-
好听的女instagram名字
好听的女instagram名字,下面就来给大家详细介绍:1、好听的女instagram名字纯英文:{01}、easy comeべeasy go{02}、ke.{03}、lose...
生活查看全文>> -
庆祝新人的结婚祝福语 祝新人结婚祝福语
1、生一世牵手,良缘不离不弃相守。国庆佳节逢新婚,真情不渝结同心。美满姻缘海枯石烂,幸福伴侣天长地久。谨祝国庆新婚同快乐!2、纸老虎,一米老鼠,点花烛,一起住;一个成了丈夫,一...
祝福语查看全文>> -
关于青春梦想的文案(青春奋斗梦想励志文案)
1、昨天再好,走不回去,明天再难,也要抬脚继续,你不勇敢,没有人替你坚强,你不疯狂,没有人帮你实现梦想。2、青春奋斗梦想的文案:3、自己不努力,谁也帮不了你;你得有足够的实力,...
句子查看全文>> -
刷保温杯够不到里面怎么办 杯子里面够不到怎么刷
我们每天都会用杯子喝水,有的还会专门用保温杯泡水喝,非常养生。尤其是长期泡茶的杯子是要经常清洗的,不然就会积聚茶垢和污渍。但是有的杯子像保温杯杯口比较窄,里面深一点的地方刷不到...
品牌查看全文>>
推荐
- 1汽车电子围栏怎么设置?318
- 2雪地轮胎沒有雪能驾驶吗354
- 3Bom茵陈蒿纯露可以淡化红血丝吗346
- 42022最吸引人的霸气个性签名361
- 5驾驶证c2升级的话可以升到多少?174
- 6红旗h7发动机国产还是进口235
- 72022最新简短正能量人生励志语录(正能量励志语录)360
- 8汽车磨合期多少公里换机油340