Python解释器路径寻找规则

时间:2022-09-26 13:29:50

Python编辑器路径寻址总结

Python编程优化

Python解释器路径寻找规则
这场表演邀请了三位角色:run.shmain.pypath.sh,拍摄场地选在了 Windows -> Git Bash
群演1号 run.sh
#!/usr/bin bash
. ./path.sh || exit -1

# demo.py无法直接找到是因为 $PATH中已经没有 工作目录
python demo.py

跳转到的地方

群演2号 path.sh
export PYTHONPATH=$PWD/define_module
export PATH="/d/Anaconda"
#export PATH="/d/Anaconda":$PWD
群演3号 demo.py
#coding=utf-8

import sys
# sys.path.append("/d/Anaconda/envs/py39/Lib/site-package/torch")

# print(sys.version, sys.path)
if __name__ == "__main__":
    print('demo')

Python编程优化

文件 IO对象嵌套

import io
with open(path , mode , encoding) as fin: 
  with open(path2 , mode , encoing ) as fout :
    for line in fin :
      ...
      fout.write()

数组 List

pop(index) # index不指定,则删除最后一个

from functools import  reduce
reduce(func , iterable , initializer=None) # func常以lambda展示  iterable可迭代对象 initializer不指定则以迭代对象第一个值为初始值

双向队列 Queue使用,来自于标准库collections.deque

from collections import deque
#初始化
d = deque('init') | d = deque(['i','n','i','t'])
# 新增API
pop()/popleft()   append()/appendleft()  extendleft  

交换两变量值a,b = b,a

python 字符串替换(正则)

# 正则方式
import re 
re.sub(r'匹配规则source', after_str , target_str , count=0 )
#replace
new_str = target_str.replace('匹配项', '替换项' , count=-1)
# count 代表替换的次数,-1代表替换所有的 符合的字符串

python 寻找解释器顺序:

外层指定:**/**/python *.py文件 则前面路径的python则为使用的解释器
# !usr/bin/python 如果上述解释器未指定,则从执行py文件头部这行代码(如果有的话)进行寻找
# $PATH/$PYTHONPATH(寻找python模块的地方)   windows则在环境变量中查找

3种for循环遍历list 方式

for item in list:
for index in range(len(list)):
for item,index in enumerate(list):

3种for循环遍历 dict 方式

for key in dict:
for key in dict.keys():
for value in dict.values():
for item in dict.items():
for key,item in dict.items():

https://www.cnblogs.com/lhx9527/p/16023075.html

python多线程打印:

import multiprocessing
import time
import os
def func(args):
      print("in func :", os.getpid())
      time.sleep(1)
      return args * args

def func2(nn):
      print(nn, "in func2 :", os.getpid())

if __name__ == "__main__":
     p = multiprocessing.Pool(5)
     for i in range(10):
         p.apply_async(func, args=(i, ), callback=func2)
     p.close()
     p.join()

如何在shell中运行python字符串代码:

python -c '''
import random
from sys import argv
for f in [1,2]:
    arr = open(argv[f]).readlines()
    random.Random(argv[3]).shuffle(arr)
    with open(argv[f] + "-sf", "w", encoding = "utf8") as fout:
        for line in arr:
            fout.write(line)
''' $scp $text $4

str.split() # 当不指定分隔符时,以空格类字符(space ,tab等)最大数量分割

参考:
https://jarvisma.gitbook.io/pythonlearn/5.4-python-mo-kuai-hua/chapter5.4.2
https://blog.csdn.net/qq_38156052/article/details/81130117
https://blog.csdn.net/qq_27825451/article/details/100552739
https://blog.csdn.net/NeverLate_gogogo/article/details/107615838
http://www.coolpython.net/python_senior/module_concept/modify-sys-path.html