其他分享
首页 > 其他分享> > Python解释器路径寻找规则

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 寻找解释器顺序:



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代表替换所有的 符合的字符串

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():

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()

由于GML锁的缘故,python多线程适用于IO任务多于CPU任务的情况,可以使用多进程:

from multiprocessing import Process
import os

# 子进程要执行的代码
def run_proc(name):
    print('Run child process %s (%s)...' % (name, os.getpid()))

if __name__=='__main__':
    print('Parent process %s.' % os.getpid())
    p = Process(target=run_proc, args=('test',))
    print('Child process will start.')
    p.start()   # 开始执行子进程,异步执行
    print('Other task RUN')
    p.join()    # 恢复同步
    print('Child process end.')

如何在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等)最大数量分割

标签:Python,编辑器,目录,Module,Java,icode9,
来源: