Python直譯器路徑尋找規則

2022-09-24 18:00:48

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

pycharm設定遠端偵錯 : 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