静音模块日志
我的脚本中有一个功能,给了我烦人的警告。此功能来自模块调用处理
,我想静音。
这是我的代码:
# Prepare the environment
import sys
import os # Ce module permet d'utiliser les fonctionnalités du système d'exploitation
from qgis.core import *
from PyQt5.QtWidgets import QApplication
app = QApplication([])
QgsApplication.setPrefixPath("/Applications/QGIS-LTR.app/Contents/MacOS", True)
os.environ["PROJ_LIB"]="/Applications/QGIS-LTR.app/Contents/Resources/proj"
QgsApplication.initQgis()
# Prepare processing framework
sys.path.append('/Applications/QGIS-LTR.app/Contents/Resources/python/plugins') # Folder where Processing is located
from processing.core.Processing import Processing
Processing.initialize()
import processing
# Run the algorithm
pwd=os.path.dirname(os.path.realpath(__file__))
def xlsx_to_csv():
import openpyxl
import pandas as pd
pd.options.mode.chained_assignment=None # Disbale CopyWarning
print('Export '+pwd+'/XLSX/input.xlsx to '+pwd+'/CSV/input.csv...')
input=pd.DataFrame()
input['Date'],input['Name'],input['UTM32_E'],input['UTM32_N']=pd.to_datetime(pd.read_excel(pwd+'/XLSX/input.xlsx',engine='openpyxl')['Date'],dayfirst=True,errors='coerce').dt.strftime('%Y-%m-%d'),pd.read_excel(pwd+'/XLSX/input.xlsx',engine='openpyxl')['Name'],pd.read_excel(pwd+'/XLSX/input.xlsx',engine='openpyxl')['UTM32_E'],pd.read_excel(pwd+'/XLSX/input.xlsx',engine='openpyxl')['UTM32_N']
input['Date'][0],input['Date'][1]='Permanent','Permanent'
input.dropna(subset=['Date'],inplace=True)
input.to_csv(pwd+'/CSV/input.csv',index=False)
xlsx_to_csv()
def windows(a,b,c):
format_tuiles=[a,b,c] # Dans l'ordre décroissant pour une bonne superposition des couches
for px in format_tuiles:
processing.run('native:refactorfields',{ 'FIELDS_MAPPING' : [{'expression': '"Date"','length': 10,'name': 'Date','precision': 0,'type': 10},{'expression': '"Name"','length': 10,'name': 'Name','precision': 0,'type': 10},{'expression': '"UTM32_E"','length': 0,'name': 'UTM32_E','precision': 0,'type': 6},{'expression': '"UTM32_N"','length': 0,'name': 'UTM32_N','precision': 0,'type': 6}], 'INPUT' : 'delimitedtext://file:///Users/pugliesipc/Desktop/extract_TSX/CSV/input.csv?type=csv&maxFields=10000&detectTypes=yes&xField=UTM32_E&yField=UTM32_N&crs=EPSG:32632&spatialIndex=no&subsetIndex=no&watchFile=no','OUTPUT':pwd+'/SHP/input.shp'})
processing.run('native:buffer',{'DISSOLVE':False,'DISTANCE':2.5,'END_CAP_STYLE':2,'INPUT':pwd+'/SHP/input.shp','JOIN_STYLE':1,'MITER_LIMIT':2,'OUTPUT':pwd+'/SHP/windows_'+str(px)+'px.shp','SEGMENTS':1})
print(str(px)+'px windows was created')
def extract_stats(a,b,c,parameter,band=1):
import pandas as pd # Ce module facilite l'exploitation des fichiers CSV
format_tuiles=[a,b,c]
output=[pd.DataFrame()]*3
radar_image=pwd+'/DATA/'+parameter
print('Extracting statistics for band '+str(band)+' from '+radar_image+'...')
for file in os.listdir(radar_image):
i=0
date=file[14:16]+'/'+file[12:14]+'/'+file[8:12]
path_to_radar_output=radar_image+'/'+file
for px in format_tuiles:
if parameter=='dB' and band==1:
parameter='K0'
elif parameter=='dB' and band==2:
parameter='K3'
elif parameter=='dB' and band==3:
parameter='K4'
elif parameter=='dB' and band==4:
parameter='K7'
processing.run('native:zonalstatisticsfb',{'COLUMN_PREFIX':'_','INPUT':pwd+'/SHP/windows_'+str(px)+'px.shp','INPUT_RASTER':path_to_radar_output,'OUTPUT':pwd+'/SHP/stat_'+str(px)+'px.shp','RASTER_BAND':band,'STATISTICS':[2,4]})
processing.run('native:savefeatures',{'DATASOURCE_OPTIONS':'','INPUT':pwd+'/SHP/stat_'+str(px)+'px.shp','LAYER_NAME':'','LAYER_OPTIONS':'','OUTPUT':pwd+'/CSV/ouput_'+str(px)+'px_'+parameter+'.csv'})
temporary_csv=pd.read_csv(pwd+'/CSV/ouput_'+str(px)+'px_'+parameter+'.csv')
output[i]=pd.concat([output[i],temporary_csv,])
i+=1
i=0
for px in format_tuiles:
output[i].to_csv(pwd+'/CSV/ouput_'+str(px)+'px_'+parameter+'.csv',index=False)
i+=1
def clean_shp():
print('Cleaning '+pwd+'/SHP/...')
for file in os.listdir(pwd+'/SHP/'):
if 'windows' in file:
continue
else:
os.remove(pwd+'/SHP/'+file)
# Exit applications
QgsApplication.exitQgis()
QApplication.exit()
其中processing
位于
/Applications/QGIS-LTR.app/Contents/Resources/python/plugins
trick:
pugliesipc@Pierres-MacBook-Air ~ % python3
Python 3.10.3 (v3.10.3:a342a49189, Mar 16 2022, 09:34:18) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import os
>>> devnull=open(os.devnull,'w')
>>> sys.stdout=devnull
>>> os.system('/Applications/QGIS-LTR.app/Contents/MacOS/bin/python3.8 /Users/pugliesipc/Desktop/extract_TSX/extract_TSX.py > /dev/null 2>&1')
>>>
此解决方案不是更方便的,因为它也丢弃了print()
...
这就是为什么我正在寻找更好的解决方案的原因。
谢谢你的宝贵时间。
I have one function in my script that gave me annoying warnings. This function is from a module call processing
and I would like to mute it.
This my code :
# Prepare the environment
import sys
import os # Ce module permet d'utiliser les fonctionnalités du système d'exploitation
from qgis.core import *
from PyQt5.QtWidgets import QApplication
app = QApplication([])
QgsApplication.setPrefixPath("/Applications/QGIS-LTR.app/Contents/MacOS", True)
os.environ["PROJ_LIB"]="/Applications/QGIS-LTR.app/Contents/Resources/proj"
QgsApplication.initQgis()
# Prepare processing framework
sys.path.append('/Applications/QGIS-LTR.app/Contents/Resources/python/plugins') # Folder where Processing is located
from processing.core.Processing import Processing
Processing.initialize()
import processing
# Run the algorithm
pwd=os.path.dirname(os.path.realpath(__file__))
def xlsx_to_csv():
import openpyxl
import pandas as pd
pd.options.mode.chained_assignment=None # Disbale CopyWarning
print('Export '+pwd+'/XLSX/input.xlsx to '+pwd+'/CSV/input.csv...')
input=pd.DataFrame()
input['Date'],input['Name'],input['UTM32_E'],input['UTM32_N']=pd.to_datetime(pd.read_excel(pwd+'/XLSX/input.xlsx',engine='openpyxl')['Date'],dayfirst=True,errors='coerce').dt.strftime('%Y-%m-%d'),pd.read_excel(pwd+'/XLSX/input.xlsx',engine='openpyxl')['Name'],pd.read_excel(pwd+'/XLSX/input.xlsx',engine='openpyxl')['UTM32_E'],pd.read_excel(pwd+'/XLSX/input.xlsx',engine='openpyxl')['UTM32_N']
input['Date'][0],input['Date'][1]='Permanent','Permanent'
input.dropna(subset=['Date'],inplace=True)
input.to_csv(pwd+'/CSV/input.csv',index=False)
xlsx_to_csv()
def windows(a,b,c):
format_tuiles=[a,b,c] # Dans l'ordre décroissant pour une bonne superposition des couches
for px in format_tuiles:
processing.run('native:refactorfields',{ 'FIELDS_MAPPING' : [{'expression': '"Date"','length': 10,'name': 'Date','precision': 0,'type': 10},{'expression': '"Name"','length': 10,'name': 'Name','precision': 0,'type': 10},{'expression': '"UTM32_E"','length': 0,'name': 'UTM32_E','precision': 0,'type': 6},{'expression': '"UTM32_N"','length': 0,'name': 'UTM32_N','precision': 0,'type': 6}], 'INPUT' : 'delimitedtext://file:///Users/pugliesipc/Desktop/extract_TSX/CSV/input.csv?type=csv&maxFields=10000&detectTypes=yes&xField=UTM32_E&yField=UTM32_N&crs=EPSG:32632&spatialIndex=no&subsetIndex=no&watchFile=no','OUTPUT':pwd+'/SHP/input.shp'})
processing.run('native:buffer',{'DISSOLVE':False,'DISTANCE':2.5,'END_CAP_STYLE':2,'INPUT':pwd+'/SHP/input.shp','JOIN_STYLE':1,'MITER_LIMIT':2,'OUTPUT':pwd+'/SHP/windows_'+str(px)+'px.shp','SEGMENTS':1})
print(str(px)+'px windows was created')
def extract_stats(a,b,c,parameter,band=1):
import pandas as pd # Ce module facilite l'exploitation des fichiers CSV
format_tuiles=[a,b,c]
output=[pd.DataFrame()]*3
radar_image=pwd+'/DATA/'+parameter
print('Extracting statistics for band '+str(band)+' from '+radar_image+'...')
for file in os.listdir(radar_image):
i=0
date=file[14:16]+'/'+file[12:14]+'/'+file[8:12]
path_to_radar_output=radar_image+'/'+file
for px in format_tuiles:
if parameter=='dB' and band==1:
parameter='K0'
elif parameter=='dB' and band==2:
parameter='K3'
elif parameter=='dB' and band==3:
parameter='K4'
elif parameter=='dB' and band==4:
parameter='K7'
processing.run('native:zonalstatisticsfb',{'COLUMN_PREFIX':'_','INPUT':pwd+'/SHP/windows_'+str(px)+'px.shp','INPUT_RASTER':path_to_radar_output,'OUTPUT':pwd+'/SHP/stat_'+str(px)+'px.shp','RASTER_BAND':band,'STATISTICS':[2,4]})
processing.run('native:savefeatures',{'DATASOURCE_OPTIONS':'','INPUT':pwd+'/SHP/stat_'+str(px)+'px.shp','LAYER_NAME':'','LAYER_OPTIONS':'','OUTPUT':pwd+'/CSV/ouput_'+str(px)+'px_'+parameter+'.csv'})
temporary_csv=pd.read_csv(pwd+'/CSV/ouput_'+str(px)+'px_'+parameter+'.csv')
output[i]=pd.concat([output[i],temporary_csv,])
i+=1
i=0
for px in format_tuiles:
output[i].to_csv(pwd+'/CSV/ouput_'+str(px)+'px_'+parameter+'.csv',index=False)
i+=1
def clean_shp():
print('Cleaning '+pwd+'/SHP/...')
for file in os.listdir(pwd+'/SHP/'):
if 'windows' in file:
continue
else:
os.remove(pwd+'/SHP/'+file)
# Exit applications
QgsApplication.exitQgis()
QApplication.exit()
This where processing
is located
/Applications/QGIS-LTR.app/Contents/Resources/python/plugins
Trick :
pugliesipc@Pierres-MacBook-Air ~ % python3
Python 3.10.3 (v3.10.3:a342a49189, Mar 16 2022, 09:34:18) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import os
>>> devnull=open(os.devnull,'w')
>>> sys.stdout=devnull
>>> os.system('/Applications/QGIS-LTR.app/Contents/MacOS/bin/python3.8 /Users/pugliesipc/Desktop/extract_TSX/extract_TSX.py > /dev/null 2>&1')
>>>
This solution is not the more convenient because it also throw away print()
...
That is why I am looking for a better solution.
Thank you for your time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论