9.6 sys模块

9.6 sys模块

  • 思考:为什么要有sys模块?sys模块有什么用?

    查看环境变量,与python交互。

1. sys.argv (重点)

当在终端使用命令'python file.py 参数1,参数2',执行python文件时候会接收参数。(重点)

#test2.py 文件
import sys

print(sys.argv)

#打开终端在test2.py文件目录下,输入:python test2.py
#输出:['test2.py']

#输入:python test2.py 222 111
# 输出:['test2.py','222','111']

sys.argv[1]='222'

# 那么就可以传入文件路径

2. 计算ATM项目文件下有几行代码

注意:count_code.py代码详见9.2os模块-小练习,统计代码行数。

终端进入count_code.py文件所在目录下
D:\ATM\test>python count_code.py D:\ATM

#输出
D:\ATM\m2.py有2代码
D:\ATM\run.py有31代码
D:\ATM\api\api.py有3代码
D:\ATM\core\check.py有28代码
D:\ATM\core\login_deco.py有16代码
D:\ATM\core\register_login.py有55代码
D:\ATM\core\shopping.py有50代码
D:\ATM\core\shopping_car.py有41代码
D:\ATM\db\db_handle.py有4代码
D:\ATM\lib\common.py有41代码
D:\ATM\m\m1.py有2代码
D:\ATM\m\__init__.py有2代码
D:\ATM\m\m3\m4.py有2代码
D:\ATM\m\m3\__init__.py有4代码
D:\ATM\test\count_code.py有23代码
D:\ATM\test\test.py有2代码

3. 获取解释器版本

import sys
print(sys.hexversion)

#输出
51120112

4. 获取当前文件的环境变量,就是模块的搜索路径(重点)


print(sys.path)
sys.path.append(path) 添加环境变量

5. sys.stdout.write()

#print(用python写的)调用sys.stdout.write()
sys.stdout.write('1243') #用C写的

#输出
1243
4

(1)实现print()

def print_copy(str,end='\n'):
    str=str+end
    sys.stdout.write(str)
    
print_copy('yhedf')

#输出
yhedf

6. sys.stdin.read()

#input底层
print(sys.stdin.read(10)) #获取输入的10个字符

# 输入:1234567890123
# 输出:1234567890

(1)实现input()

# 
def input_copy():
    sys.stdin.read() 
input('请输入>>')

#终端输出:
请输入>> 123456
'123456'
posted @ 2025-09-01 21:36  bokebanla  阅读(5)  评论(0)    收藏  举报