python代码没错但运行不出来

Python0433

python代码没错但运行不出来,第1张

     python代码没错但运行不出来是什么原因呢?不知道的小伙伴来看看今天的分享吧!

      1、python代码没错但运行不出来的原因:

      某项目中使用python脚本方式将日志文件中的数据持续的转换格式输出到另一文件中以供其他日志分析应用使用。但是当后台运行采取重定向方式输出到某一文件时,发现并没有内容输出,命令如下:

      pythonxxx.py>xxx.log&

      测试发现,当前台直接输出到终端时正常,使用后台运行重定向的方式输出到文件中时无法输出。

      2、解决办法:

      发现是在程序运行时,输出有缓存,只有当程序运行结束或者缓冲区满后才会输出。因为程序是一致在运行的所以不可能等待程序结束在输出。并且要求是有实时性的所以等缓冲区满输出的方式也不可取。

      所以采用在python运行时加上-u参数,如:

      python-uxxx.py>xxx.log&

      -u参数的意义是不使用缓冲的方式输入输出

      详细如下:

      Forcestdin,stdoutandstderrtobetotallyunbuffered.Onsystemswhereitmatters,alsoputstdin,stdoutandstderrinbinarymode.Notethatthereisinternalbufferinginxreadlines(),readlines()andfile-objectiterators("forlineinsys.stdin”)whichisnotinfluencedbythisoption.Toworkaroundthis,youwillwanttouse"sys.stdin.readline()”insidea"while1:”loop.

      补充知识:python中运行代码时没有报错但是也没有输出而且还有exitcode0的结束标志

      如下所示:

      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:Saslauthduser:/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:PulseAudioSystemDaemon:/var/run/pulse:/sbin/nologin

      但是输出的结果是

      Processfinishedwithexitcode0

      后来排查发现原来是解释器的问题

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

      #####如何查看解释器

      点file?C>newprojects

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

      点击3然后选择你已经下载好的解释器即可。

      以上就是今天的分享了,希望可以帮助到大家。

1. python运行结束出现:process finished with exit code 0

说明,程序正常运行完。

例如:test1.py文件如下代码

a = 1/1

print a

运行后出现:Process finished with exit code 0

2. 如果出现:

process finished with exit code 1

说明程序出错,也就是代码有问题。

例如:test2.py

a = 1/0

print a

运行后出现:

Traceback (most recent call last):

File "/Users/pwd/work/project/AnyData/data/test3.py", line 36, in <module>

a = 1/0

ZeroDivisionError: integer division or modulo by zero    [报错:0不能被除]

Process finished with exit code 1

通常是因为语法错误,你可以检查是不是形如:

print ‘Hello, World!'

print ('Hello, World!')

其中尤其需要注意,print 必须全部是小写,否则系统认不出,就会报错。