在Python中显示代码行数可以通过以下几种方法实现:
1. 使用`traceback`模块:
```python
import traceback
try:
your code here
except Exception as e:
print(traceback.format_exc())
2. 使用`LineNumber.py`扩展:
下载`LineNumber.py`文件。
将文件复制到Python安装目录下的`idlelib`目录。
编辑`config-extensions.def`文件,添加如下配置参数:
```
[LineNumbers]
enable=1
enable_editor=1
enable_shell=0
visible=1
保存文件并重启Python IDLE。
3. 使用第三方库,如`linecounter`:
```python
from linecounter import LineCounter
counter = LineCounter()
total_lines = counter.count_lines("example.py")
print(f"总行数:{total_lines}")
4. 使用Python内置函数统计文件行数:
```python
def count_lines(file_path):
line_count = 0
with open(file_path, 'r') as file:
for line in file:
line_count += 1
return line_count
file_path = 'example.txt'
line_count = count_lines(file_path)
print(f"文件行数为:{line_count} 行。"
```python
import sys
import os
import codecs
from _pyio import open
totalCount = 0
fileType = '.java'
descLineBegin = '//'
descBlockBegin = r'/\*\*'
descBlockEnd = r'\*/'
fileEncode = 'utf-8'
def main():
DIR = os.getcwd()
if len(sys.argv) >= 2:
DIR = sys.argv
if os.path.exists(DIR) and os.path.isdir(DIR):
print('target directory is %s' % DIR)
countDir(DIR)
print('total code line is %d' % totalCount)
def countDir(dirPath):
for root, dirs, files in os.walk(dirPath):
for file in files:
if file.endswith(fileType):
filePath = os.path.join(root, file)
with codecs.open(filePath, 'r', fileEncode) as f:
for line in f:
if not line.strip().startswith(descLineBegin) and not line.strip().startswith(descBlockBegin) and not line.strip().endswith(descBlockEnd):
totalCount += 1
if __name__ == "__main__":
main()
以上方法可以帮助你在Python中显示或统计代码行数