Maya script that renders to frame buffer keeps grabbing focus on windows - python

I have a script in Maya (python) that renders a series of frames to the V-ray frame buffer, one for each render layer. It is working well, but when switching render layers and launching the next render, Maya grabs focus, interrupting whatever task the artist had moved on to while the script was running. I would like this to be a background task. Maya is running on Windows.
import maya
import maya.cmds as cmds
import re
from functools import partial
import sys
from datetime import datetime
global cancel
cancel = 0
print 'batch_review'
def no_cam_window_popup(no_cam_set_list):
#print no_cam_set_list
cmds.window(title = 'WARNING: NO CAMERAS LINKED TO LAYERS', width = 300, height = 75, sizeable = False)
cmds.columnLayout("mainColumn", adjustableColumn = True)
cmds.rowLayout("nameRowLayout01", numberOfColumns = 15, parent = "mainColumn")
cmds.text(label = ("no cam set for layers:"))
for layer in no_cam_set_list:
cmds.text(label = ('' + layer + ', '),font = 'boldLabelFont')
cmds.showWindow()
def renderThumbs(checkBoxLow,checkBoxMid,checkBoxHigh,checkBoxRenderRegion,intField_res,floatField_thrhld,*args):
global cancel
cams = cmds.ls(type = "camera")
cancel = 0
popup_win = 0
no_cam_set_list = []
cmds.loadPlugin('vrayformaya', quiet=True)
cmds.pluginInfo('vrayformaya', edit=True, autoload=True)
cmds.setAttr("defaultRenderGlobals.ren", "vray", type = "string")
curLay = cmds.editRenderLayerGlobals( currentRenderLayer = True, query = True )
changeLay = curLay
rls = cmds.ls(type = "renderLayer")
renCams = cmds.ls(type = "camera")
renCam = "persp"
lowBut = cmds.checkBox(checkBoxLow,value = True, query = True)
midBut = cmds.checkBox(checkBoxMid,value = True, query = True)
highBut = cmds.checkBox(checkBoxHigh,value = True, query = True)
globopt_cache_geom_plugins = cmds.getAttr('vraySettings.globopt_cache_geom_plugins')
#print 'globopt_cache_geom_plugins = ',globopt_cache_geom_plugins
print " "
print "-- batch_review --"
res = cmds.intField(intField_res, v = True, query = True)
thr = cmds.floatField(floatField_thrhld, v = True,query = True)
if lowBut == 1:
cmds.setAttr("vraySettings.dmcThreshold",thr)
cmds.setAttr("vraySettings.width", res)
cmds.setAttr("vraySettings.height", res)
cmds.setAttr("vraySettings.globopt_cache_geom_plugins",1)
cmds.setAttr("vraySettings.globopt_ray_maxIntens_on",1)
#cmds.setAttr('vraySettings.globopt_cache_geom_plugins',globopt_cache_geom_plugins)
print " "
print "---"
print "quality = %s, dmcThreshold = %s"%(res,thr)
if midBut == 1:
cmds.setAttr("vraySettings.dmcThreshold",thr)
cmds.setAttr("vraySettings.width", res)
cmds.setAttr("vraySettings.height", res)
cmds.setAttr("vraySettings.globopt_cache_geom_plugins",1)
cmds.setAttr("vraySettings.globopt_ray_maxIntens_on",1)
#cmds.setAttr('vraySettings.globopt_cache_geom_plugins',globopt_cache_geom_plugins)
print " "
print "---"
print "quality = %s, dmcThreshold = %s"%(res,thr)
if highBut == 1:
cmds.setAttr("vraySettings.dmcThreshold",thr)
cmds.setAttr("vraySettings.width", res)
cmds.setAttr("vraySettings.height", res)
cmds.setAttr("vraySettings.globopt_cache_geom_plugins",1)
cmds.setAttr("vraySettings.globopt_ray_maxIntens_on",1)
#cmds.setAttr('vraySettings.globopt_cache_geom_plugins',globopt_cache_geom_plugins)
print " "
print "---"
print "quality = %s, dmcThreshold = %s"%(res,thr)
print "--- "
print " "
for rl in rls:
found_cam = 0
if rl != "defaultRenderLayer" and cancel == 0:
rlState = cmds.getAttr(rl + ".renderable")
if rlState == 1:
print ' '
print "rende layer = ",rl
cmds.editRenderLayerGlobals( currentRenderLayer = rl )
for cam in cams:
camState = cmds.getAttr(cam + ".renderable")
if camState == 1:
rrState = cmds.checkBox(checkBoxRenderRegion,value = True,query = True)
reg = cmds.vray("vfbControl","-getregion")
if rrState == 0:
cmds.vray("vfbControl","-setregion","reset")
if rrState == 1:
cmds.vray("vfbControl","-setregionenabled",1)
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
mayaString = "renderWindowRenderCamera render renderView " + cam
print 'using ' + cam + ' for ' + rl
maya.mel.eval(mayaString)
cmds.vray("vfbControl", "-historysave")
cmds.vray("vfbControl", "-historyselect",0)
dte = datetime.now().strftime('%H:%M:%S')
editStr = dte + " ,render layer: " + rl + " , " + "cam: " + cam
cmds.vray("vfbControl", "-historycomment", editStr)
print " "
found_cam = 1
if found_cam == 0:
print 'no camera link found, using persp cam for ',rl
cam = 'persp'
rrState = cmds.checkBox(checkBoxRenderRegion,value = True,query = True)
reg = cmds.vray("vfbControl","-getregion")
if rrState == 0:
cmds.vray("vfbControl","-setregion","reset")
if rrState == 1:
cmds.vray("vfbControl","-setregionenabled",1)
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
mayaString = "renderWindowRenderCamera render renderView " + cam
maya.mel.eval(mayaString)
cmds.vray("vfbControl", "-historysave")
cmds.vray("vfbControl", "-historyselect",0)
dte = datetime.now().strftime('%H:%M:%S')
editStr = dte + " ,render layer: " + rl + " , " + "cam: " + cam
cmds.vray("vfbControl", "-historycomment", editStr)
popup_win = 1
no_cam_set_list.append(rl)
#if popup_win == 1:
#no_cam_window_popup(no_cam_set_list)
def checkBoxCheckLow(checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld,*args):
global cancel
lowButVal = cmds.checkBox(checkBoxLow,value = True, query = True)
midButVal = cmds.checkBox(checkBoxMid,value = True, query = True)
highButVal = cmds.checkBox(checkBoxHigh,value = True, query = True)
cmds.checkBox(checkBoxMid,value = False, edit = True)
cmds.checkBox(checkBoxHigh,value = False, edit = True)
cmds.intField(intField_res, v = 800,edit = True)
cmds.floatField(floatField_thrhld, v = .1,edit = True )
cancel = 0
def checkBoxCheckMid(checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld,*args):
global cancel
lowButVal = cmds.checkBox(checkBoxLow,value = True, query = True)
midButVal = cmds.checkBox(checkBoxMid,value = True, query = True)
highButVal = cmds.checkBox(checkBoxHigh,value = True, query = True)
cmds.checkBox(checkBoxLow,value = False, edit = True)
cmds.checkBox(checkBoxHigh,value = False, edit = True)
cmds.intField(intField_res, v = 1000,edit = True)
cmds.floatField(floatField_thrhld, v = .5,edit = True )
cancel = 0
def checkBoxCheckHigh(checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld,*args):
global cancel
lowButVal = cmds.checkBox(checkBoxLow,value = True, query = True)
midButVal = cmds.checkBox(checkBoxMid,value = True, query = True)
highButVal = cmds.checkBox(checkBoxHigh,value = True, query = True)
cmds.checkBox(checkBoxLow,value = False, edit = True)
cmds.checkBox(checkBoxMid,value = False, edit = True)
cmds.intField(intField_res, v = 2000,edit = True)
cmds.floatField(floatField_thrhld, v = .008,edit = True )
cancel = 0
def checkBoxAOVchange(checkBoxAOV,*args):
checkBoxAOVval = cmds.checkBox(checkBoxAOV,value = True,query = True)
if checkBoxAOVval == 1:
cmds.setAttr("vraySettings.relements_enableall", 1)
if checkBoxAOVval == 0:
cmds.setAttr("vraySettings.relements_enableall", 0)
def rrCheckbox(checkBoxRenderRegion,reg,*args):
global gReg
zeroes = ['0','0','0','0']
tRes = cmds.vray("vfbControl","-getregion")
if tRes != zeroes:
gReg = tRes
rrstate = cmds.checkBox(checkBoxRenderRegion,value = True,query = True)
if rrstate == 0:
if gReg != zeroes:
cmds.vray("vfbControl","-setregion",gReg[0],gReg[1],gReg[2],gReg[3])
else:
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
cmds.vray("vfbControl","-setregion","reset")
if rrstate == 1:
cmds.vray("vfbControl","-setregionenabled",1)
if gReg != zeroes:
cmds.vray("vfbControl","-setregion",gReg[0],gReg[1],gReg[2],gReg[3])
else:
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
return(reg)
def cancelOPs(*args):
global cancel
cancel = 1
raise Exception("quitting renders")
def set_threshhold(floatField_thrhld,*args):
threshhold_value = cmds.floatField(floatField_thrhld,value = True,query = True)
cmds.setAttr('vraySettings.dmcThreshold',threshhold_value)
def set_resolution(intField_res,*args):
intField_res_value = cmds.intField(intField_res,value = True,query = True)
cmds.setAttr('vraySettings.width',intField_res_value)
cmds.setAttr('vraySettings.height',intField_res_value)
def renthumbsWin():
name = "Batch_Review"
global gReg
gReg = ('0','0','0','0')
zeroes = ('0','0','0','0')
windowSize = (200,100)
if (cmds.window(name, exists = True)):
cmds.deleteUI(name)
window = cmds.window(name, title = name, width = 350, height = 50,bgc = (.2,.2,.2), s = False)
cmds.columnLayout("mainColumn", adjustableColumn = True)
cmds.rowLayout("nameRowLayout01", numberOfColumns = 15, parent = "mainColumn")
cmds.text(label = "preset quality: ")
checkBoxLow = cmds.checkBox(label = "low", value = False)
checkBoxMid = cmds.checkBox(label = "mid", value = True,)
checkBoxHigh = cmds.checkBox(label = "high", value = False)
cmds.text(label = " ")
cmds.text(label = "resolution: ")
intField_res = cmds.intField(v = 1000,width = 45)
#print 'intField_res = ',intField_res
cmds.intField(intField_res, changeCommand = partial(set_resolution,intField_res),edit = True)
cmds.text(label = " ")
cmds.text(label = "threshold: ")
floatField_thrhld = cmds.floatField(v = .5,width = 45)
cmds.floatField(floatField_thrhld, changeCommand = partial(set_threshhold,floatField_thrhld),edit = True)
cmds.checkBox(checkBoxLow, changeCommand = partial(checkBoxCheckLow,checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld), edit = True)
cmds.checkBox(checkBoxMid, changeCommand = partial(checkBoxCheckMid,checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld),edit = True)
cmds.checkBox(checkBoxHigh, changeCommand = partial(checkBoxCheckHigh,checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld),edit = True)
cmds.rowLayout("nameRowLayout02", numberOfColumns = 10, parent = "mainColumn")
cmds.text(label = " ")
cmds.rowLayout("nameRowLayout03", numberOfColumns = 5, parent = "mainColumn")
renderButton = cmds.button(label = "render",width = 100, bgc = (.6,.8,1) )
cmds.text(label = " ")
cmds.button(label = "cancel renders", command = partial(cancelOPs),bgc = (1,.3,.3) )
cmds.rowLayout("nameRowLayout04", numberOfColumns = 10, parent = "mainColumn")
cmds.text(label = " ")
cmds.rowLayout("nameRowLayout05", numberOfColumns = 10, parent = "mainColumn")
checkBoxRenderRegion = cmds.checkBox(label = "use render region", value = False)
cmds.text(label = " ")
cmds.text(label = " ")
reg = cmds.vray("vfbControl","-getregion")
if reg != gReg and reg != zeroes:
gReg = reg
cmds.vray("vfbControl","-setregion","reset")
cmds.checkBox(checkBoxRenderRegion,changeCommand = partial(rrCheckbox,checkBoxRenderRegion,reg),edit = True)
cmds.rowLayout("nameRowLayout06", numberOfColumns = 10, parent = "mainColumn")
AOVstate = cmds.getAttr("vraySettings.relements_enableall")
checkBoxAOV = cmds.checkBox(label = "elements", value = AOVstate)
cmds.checkBox(checkBoxAOV,changeCommand = partial(checkBoxAOVchange,checkBoxAOV),edit = True)
cmds.button(renderButton,command = partial(renderThumbs,checkBoxLow,checkBoxMid,checkBoxHigh,checkBoxRenderRegion,intField_res,floatField_thrhld),edit = True)
cmds.showWindow()
def main():
renthumbsWin()
main()

Related

'timestamp' messages appeared on my terminal, but i didn't code print('timestamp')

enter image description hereI made my autobot for coin trade.
I'm using iterm2 terminal to operate my code.
But there's some problem I don't understand.
first I use the same fuction by changing parameter, symbolname etc.
but on the terminal window for A coin, there's only 'timestamp' message.
i can't tell if it is error or not because there's no error message
and i didn't code print('timestamp')
on the other terminal windows for other coin, there's no such a message.
I guess my explanation is not enough.
but if you have any idea about this kind of situations, please tell me.
I'm using python.
thank you already!!
sometimes, although i didn't change anytihng.
'timestamp' message was disappeared.
enter image description here
enter code here
def runBot(symbol, second=int):
try:
subtitle = 'B'
fourth_interval = '30m'
symbol = symbol
path = path
df_1 = callChart(exchange=exchange, symbol=symbol, interval='15m')
df_2 = callChart(exchange=exchange, symbol=symbol, interval='5m')
df_3 = callChart(exchange=exchange, symbol=symbol, interval='1m')
df_4 = callChart(exchange=exchange, symbol=symbol, interval='30m')
df_5 = callChart(exchange=exchange, symbol=symbol, interval='1h')
df_6 = callChart(exchange=exchange, symbol=symbol, interval='4h')
df_7 = callChart(exchange=exchange, symbol=symbol, interval='2h')
n4hma2 = df_6.ma20[-1]
n4hma6 = df_6.ma60[-1]
n4hma8 = df_6.ma80[-1]
p4h_rsi = df_6.rsi[-2]
p4h_open = df_6.open[-2]
p4h_close = df_6.close[-2]
n1hma2 = df_5.ma20[-1]
n1hma6 = df_5.ma60[-1]
n1hma8 = df_5.ma80[-1]
n1h_low = df_5.low[-1]
n1h_high = df_5.high[-1]
n1h_open = df_5.open[-1]
p1h_rsi = df_5.rsi[-2]
p1hma2 = df_5.ma20[-2]
p1hma6 = df_5.ma60[-2]
p1hma8 = df_5.ma80[-2]
p1h_close = df_5.close[-2]
n30ma2 = df_4.ma20[-1]
n30ma6 = df_4.ma60[-1]
n30ma8 = df_4.ma80[-1]
n30_high = df_4.high[-1]
n30_low = df_4.low[-1]
n30_open = df_4.open[-1]
p30_rsi = df_4.rsi[-2]
p30_rsi = df_4.rsi[-2]
p30_close = df_4.close[-2]
pp30_close = df_4.close[-3]
ppp30_close = df_4.close[-4]
p30ma2 = df_4.ma20[-2]
p30ma6 = df_4.ma60[-2]
p30ma8 = df_4.ma80[-2]
pp30ma2 = df_4.ma20[-4]
pp30ma6 = df_4.ma60[-4]
pp30ma8 = df_4.ma80[-4]
ppp30ma2 = df_4.ma20[-4]
ppp30ma6 = df_4.ma60[-4]
ppp30ma8 = df_4.ma80[-4]
p4_30ma2 = df_4.ma20[-5]
p4_30ma6 = df_4.ma60[-5]
p4_30ma8 = df_4.ma80[-5]
n_price = df_1.close[-1]
n15ma2 = df_1.ma20[-1]
n15ma6 = df_1.ma60[-1]
n15ma8 = df_1.ma80[-1]
p15_close = df_1.close[-2]
p15_open = df_1.open[-2]
n15_high = df_1.high[-1]
n15_low = df_1.low[-1]
p15ma2 = df_1.ma20[-2]
p15ma6 = df_1.ma60[-2]
p15ma8 = df_1.ma80[-2]
n5ma2 = df_2.ma20[-1]
n5ma6 = df_2.ma60[-1]
n5ma8 = df_2.ma80[-1]
n5_high = df_2.high[-1]
n5_low = df_2.low[-1]
p5ma2 = df_2.ma20[-2]
p5ma6 = df_2.ma60[-2]
p5ma8 = df_2.ma80[-2]
p5_close = df_2.close[-2]
n1ma2 = df_3.ma20[-1]
n1ma6 = df_3.ma60[-1]
n1ma8 = df_3.ma80[-1]
p1m_close = df_3.close[-2]
p1ma2 = df_3.ma20[-2]
p1ma6 = df_3.ma60[-2]
p1ma8 = df_3.ma80[-2]
n2hma2 = df_7.ma20[-1]
n2hma6 = df_7.ma60[-1]
n2hma8 = df_7.ma80[-1]
now = datetime.datetime.utcnow() + datetime.timedelta(hours=9)
now_date = datetime.date(now.year, now.month, now.day)
now_time = datetime.time(now.hour, now.minute, now.second)
what_day = now.weekday()
timestamp = time.mktime(datetime.datetime.strptime(str(f'{now_date} {now_time}'), '%Y-%m-%d %H:%M:%S').timetuple())
mt4 = datetime.datetime.utcnow() + datetime.timedelta(hours=3)
mt4_date = datetime.date(mt4.year, mt4.month, mt4.day)
mt4_time = datetime.time(mt4.hour, mt4.minute, mt4.second)
total_balance = exchange.fetch_balance()['USDT']['total']
total_balance2 = exchange2.fetch_balance()['USDT']['total']
total_balance5 = exchange5.fetch_balance()['USDT']['total']
print(colors.fg.blue, f'{subtitle}', colors.reset, colors.fg.green, f'{symbol}', colors.reset, f'{n_price}', colors.fg.yellow, f'{now_date} {now_time}', colors.reset)

python / I think It can write it briefly, but I don't know

This is the code I wrote.
Enter data of JSON into EXEL.
I tried .format() but failed.
I think it's too inefficient.
What should I do to make it simple?
Ask for help
DATA:
{"Y": ["1950","1951","1952","1953","1954","1955"],
"DATA":[
{"M":"1월",
"DATA1":164, "DATA2":173, "DATA3":2374,
"DATA4":183, "DATA5":186, "DATA6":2374,
"DATA7":151, "DATA8":145
},
{"M":"2월",
"DATA1":174, "DATA2":138, "DATA3":2374,
"DATA4":178, "DATA5":104, "DATA6":2374,
"DATA7":178, "DATA8":142
},
{"M":"3월",
"DATA1":135,"DATA2":173,"DATA3":2374,
"DATA4":104,"DATA5":176,"DATA6":2374,
"DATA7":134,"DATA8":178
},
{"M":"4월",
"DATA1":178,"DATA2":102,"DATA3":2374,
"DATA4":175,"DATA5":142,"DATA6":2374,
"DATA7":101,"DATA8":112
},
{"M":"5월",
"DATA1":135,"DATA2":168,"DATA3":2374,
"DATA4":127,"DATA5":104,"DATA6":2374,
"DATA7":167,"DATA8":183
},
{"M":"6월",
"DATA1":102,"DATA2":175,"DATA3":2374,
"DATA4":178,"DATA5":190,"DATA6":2374,
"DATA7":197,"DATA8":180},
{"M":"7월",
"DATA1":135,"DATA2":105,"DATA3":2374,
"DATA4":168,"DATA5":145,"DATA6":2374,
"DATA7":199,"DATA8":140},
{"M":"8월",
"DATA1":178,"DATA2":137,"DATA3":2374,
"DATA4":100,"DATA5":168,"DATA6":2374,
"DATA7":142,"DATA8":199
},
{"M":"9월",
"DATA1":135,"DATA2":175,"DATA3":2374,
"DATA4":135,"DATA5":124,"DATA6":2374,
"DATA7":176,"DATA8":125
},
{"M":"10월",
"DATA1":140,"DATA2":105,"DATA3":2374,
"DATA4":133,"DATA5":133,"DATA6":2374,
"DATA7":104,"DATA8":104
},
{"M":"11월",
"DATA1":199,"DATA2":178,"DATA3":2374,
"DATA4":170,"DATA5":157,"DATA6":2374,
"DATA7":178,"DATA8":167
},
{"M":"12월",
"DATA1":138,"DATA2":196,"DATA3":2374,
"DATA4":109,"DATA5":107,"DATA6":2374,
"DATA7":100,"DATA8":104
}
],
"단위":"건","오차":"5%"
}
CODE:
import json
from openpyxl import Workbook
wb = Workbook()
wb.save('test1.xlsx')
sheet1 = wb.active
sheet1.title = 'abcd'
with open('getdata.JSON', encoding='UTF8') as resp:
project_info = json.load(resp)
sheet1['B10'] = project_info['Y'][0]
sheet1['C10'] = project_info['Y'][1]
sheet1['D10'] = project_info['Y'][2]
sheet1['E10'] = project_info['Y'][3]
sheet1['F10'] = project_info['Y'][4]
sheet1['G10'] = project_info['Y'][5]
sheet1['A11'] = project_info['DATA'][0].get('M')
sheet1['A12'] = project_info['DATA'][1].get('M')
sheet1['A13'] = project_info['DATA'][2].get('M')
sheet1['A14'] = project_info['DATA'][3].get('M')
sheet1['A15'] = project_info['DATA'][4].get('M')
sheet1['A16'] = project_info['DATA'][5].get('M')
sheet1['A17'] = project_info['DATA'][6].get('M')
sheet1['A18'] = project_info['DATA'][7].get('M')
sheet1['A19'] = project_info['DATA'][8].get('M')
sheet1['A20'] = project_info['DATA'][9].get('M')
sheet1['A21'] = project_info['DATA'][10].get('M')
sheet1['A22'] = project_info['DATA'][11].get('M')
sheet1['B11'] = project_info['DATA'][0].get('DATA1')
sheet1['B12'] = project_info['DATA'][1].get('DATA1')
sheet1['B13'] = project_info['DATA'][2].get('DATA1')
sheet1['B14'] = project_info['DATA'][3].get('DATA1')
sheet1['B15'] = project_info['DATA'][4].get('DATA1')
sheet1['B16'] = project_info['DATA'][5].get('DATA1')
sheet1['B17'] = project_info['DATA'][6].get('DATA1')
sheet1['B18'] = project_info['DATA'][7].get('DATA1')
sheet1['B19'] = project_info['DATA'][8].get('DATA1')
sheet1['B20'] = project_info['DATA'][9].get('DATA1')
sheet1['B21'] = project_info['DATA'][10].get('DATA1')
sheet1['B22'] = project_info['DATA'][11].get('DATA1')
sheet1['C11'] = project_info['DATA'][0].get('DATA2')
sheet1['C12'] = project_info['DATA'][1].get('DATA2')
sheet1['C13'] = project_info['DATA'][2].get('DATA2')
sheet1['C14'] = project_info['DATA'][3].get('DATA2')
sheet1['C15'] = project_info['DATA'][4].get('DATA2')
sheet1['C16'] = project_info['DATA'][5].get('DATA2')
sheet1['C17'] = project_info['DATA'][6].get('DATA2')
sheet1['C18'] = project_info['DATA'][7].get('DATA2')
sheet1['C19'] = project_info['DATA'][8].get('DATA2')
sheet1['C20'] = project_info['DATA'][9].get('DATA2')
sheet1['C21'] = project_info['DATA'][10].get('DATA2')
sheet1['C22'] = project_info['DATA'][11].get('DATA2')
sheet1['D11'] = project_info['DATA'][0].get('DATA4')
sheet1['D12'] = project_info['DATA'][1].get('DATA4')
sheet1['D13'] = project_info['DATA'][2].get('DATA4')
sheet1['D14'] = project_info['DATA'][3].get('DATA4')
sheet1['D15'] = project_info['DATA'][4].get('DATA4')
sheet1['D16'] = project_info['DATA'][5].get('DATA4')
sheet1['D17'] = project_info['DATA'][6].get('DATA4')
sheet1['D18'] = project_info['DATA'][7].get('DATA4')
sheet1['D19'] = project_info['DATA'][8].get('DATA4')
sheet1['D20'] = project_info['DATA'][9].get('DATA4')
sheet1['D21'] = project_info['DATA'][10].get('DATA4')
sheet1['D22'] = project_info['DATA'][11].get('DATA4')
sheet1['E11'] = project_info['DATA'][0].get('DATA5')
sheet1['E12'] = project_info['DATA'][1].get('DATA5')
sheet1['E13'] = project_info['DATA'][2].get('DATA5')
sheet1['E14'] = project_info['DATA'][3].get('DATA5')
sheet1['E15'] = project_info['DATA'][4].get('DATA5')
sheet1['E16'] = project_info['DATA'][5].get('DATA5')
sheet1['E17'] = project_info['DATA'][6].get('DATA5')
sheet1['E18'] = project_info['DATA'][7].get('DATA5')
sheet1['E19'] = project_info['DATA'][8].get('DATA5')
sheet1['E20'] = project_info['DATA'][9].get('DATA5')
sheet1['E21'] = project_info['DATA'][10].get('DATA5')
sheet1['E22'] = project_info['DATA'][11].get('DATA5')
sheet1['F11'] = project_info['DATA'][0].get('DATA7')
sheet1['F12'] = project_info['DATA'][1].get('DATA7')
sheet1['F13'] = project_info['DATA'][2].get('DATA7')
sheet1['F14'] = project_info['DATA'][3].get('DATA7')
sheet1['F15'] = project_info['DATA'][4].get('DATA7')
sheet1['F16'] = project_info['DATA'][5].get('DATA7')
sheet1['F17'] = project_info['DATA'][6].get('DATA7')
sheet1['F18'] = project_info['DATA'][7].get('DATA7')
sheet1['F19'] = project_info['DATA'][8].get('DATA7')
sheet1['F20'] = project_info['DATA'][9].get('DATA7')
sheet1['F21'] = project_info['DATA'][10].get('DATA7')
sheet1['F22'] = project_info['DATA'][11].get('DATA7')
sheet1['G11'] = project_info['DATA'][0].get('DATA8')
sheet1['G12'] = project_info['DATA'][1].get('DATA8')
sheet1['G13'] = project_info['DATA'][2].get('DATA8')
sheet1['G14'] = project_info['DATA'][3].get('DATA8')
sheet1['G15'] = project_info['DATA'][4].get('DATA8')
sheet1['G16'] = project_info['DATA'][5].get('DATA8')
sheet1['G17'] = project_info['DATA'][6].get('DATA8')
sheet1['G18'] = project_info['DATA'][7].get('DATA8')
sheet1['G19'] = project_info['DATA'][8].get('DATA8')
sheet1['G20'] = project_info['DATA'][9].get('DATA8')
sheet1['G21'] = project_info['DATA'][10].get('DATA8')
sheet1['G22'] = project_info['DATA'][11].get('DATA8')
wb.save('test1.xlsx')
sheet = ['B10', 'C10', 'D10', 'E10', 'F10', 'G10']
for i in range(0,5,1):
sheet1[sheet[i]] = project_info['Y'][i]
_dict = {"A":"M", "B":"DATA1", "C":"DATA2", "D":"DATA4", "E":"DATA5", "F":"DATA7", "G":"DATA8" }
for k, v in _dict.items():
for i in range(0, 11, 1):
key = k + str(i+11)
sheet1[key] = project_info['DATA'][i].get(v)
You should be able to use a nested loop over your letters
This will loop over the letters b to g (indexes 1 to 7 of the alphabet, adjust as required) and then creating 12 entries per letter
import string
for idx, letter in enumerate(string.ascii_lowercase[1:7]):
for i in range(12):
sheet1[f'{letter}{i+11}'] = project_info['DATA'][i].get(f'DATA{idx + 1}')
(Written on a phone, apologies for formatting)
You can use similar loops for the a column and y info

How do I use arguments?

I'm trying to select multiple curve cvs
these are my function's codes
this is setArg Func:
import maya.cmds as mc from functools import partial
def setArg(CTS, option, *args):
option = mc.radioButtonGrp(CTS, q=True, select=True)
if option == 1:
cvToSel = 'first'
print cvToSel
elif option == 2:
cvToSel = 'last'
print cvToSel
return cvToSel
this is execute Func:
def execute(cvToSel, *args):
newSel = []
curves = mc.listRelatives (type = 'nurbsCurve', shapes = True)
if not curves:
print ('no curves selected')
#mc.select(clear = True)
#print curves
for crv in curves:
len = mc.getAttr(crv+'.cp', s=True, multiIndices=True)
cvSelect = mc.intFieldGrp('numberOfCvs', q = True, value1 = True)
numCv = len - cvSelect
if cvToSel == 'last':
newSel = mc.select(crv+'.cv[%d'%numCv +':%d]'%len, tgl = True)
elif cvToSel == 'first':
newSel = mc.select(crv+'.cv[0' + ':%d]'%cvSelect, tgl = True)
#mc.select(newSel, replace = True)
this is ui Func:
def ui():
if mc.window('CV_Select', exists = True):
mc.deleteUI('CV_Select')
cvWin = mc.window('CV_Select', mxb = False)
mc.columnLayout( adjustableColumn = True )
mc.text( label = 'select curves' )
mc.intFieldGrp( 'numberOfCvs', label = 'Number Of Cvs', value1 = 10 )
ButtonOne = mc.radioButtonGrp( label='Type', labelArray2=['First CVs', 'Last CVs'], numberOfRadioButtons = 2)
mc.button( label = 'Select CVs', command = partial(execute, ButtonOne), align = 'center', aop = True)
mc.showWindow('CV_Select')
ui()
How do I use arguments?
first dont use 'len' to store a variable. it is a python function really useful....
Here is a way to do it. You need to put your select function outside your loop
You could use -add flag but it can be really slow
Store first cvs into a variable :
(i dont have maya until Monday but I hope it will help)
sel_curves = mc.ls(sl=1, dag=1, type='nurbsCurve')
if sel_curves:
to_sel = []
cvSelect = mc.intFieldGrp('numberOfCvs', q = True, value1 = True)
for c in sel_curves:
cvs = mc.ls(c+'.cv[:]', fl=True)
nb_cvs = len(cvs)
if cvSelect > nb_cvs:
nb_cvs = cvSelect
if cvToSel == 'last':
to_sel += cvs[cvSelect:]
elif cvToSel == 'first':
to_sel += cvs[:cvSelect]
cmds.select(to_sel, tgl = True)
--- EDIT ---
Just to answer your comment question :
def execute(CTS,*args):
cvToSel = setArg(CTS)

Ploting results from Gurobi python

import os
import sys
import math
import cvxopt as cvx
import picos as pic
import pandas as pd
import matplotlib.pyplot as plt
from gurobipy import *
from statsmodels.tsa.arima_model import ARIMA
import numpy as np
from scipy import *
#import DeferableLoad
OPTmodel = Model('OPTIMIZER')
#general parameters
Tamb =22
N = 1440 # maximum iteration
i = range(1, N)
COP= 3.4 # Coeffient of performance
'''
Prediction need to be added here
'''
# Datacenter room defintion
R = 10 #length of room
B = 7
H = 9 #Height of room
L = 10
dT = 60
A = 2*((L*B)+(B*H)+(H*L))
Thick = 0.33 # thickness of wall
k = 0.7 # thermal conductivity of wall
mAir = 1.2 * (L * B * H)
C = 718
landa = k * A / Thick
a0 = 0.05 / dT
a1 = 1
ki = math.exp(-(landa * 60) / (mAir * C)) # value that constant and its related to property of room
kc = (1 - ki) * a0
ko = (1 - ki) * a1
kp = (1 - ki) * (COP / landa)
Tmin= 18
Tmax= 27
Tamb= 22
PcoolingRated = 100
Pbess_rated = 30.462
Pbess_ratedN = -30.462
Ebess_min = 0
Ebess_max = 300
with open ('Pcooling.csv','r') as f:
Pcooling = []
for line in f:
Pcooling.append(line)
f.close()
with open ('ITpower.csv','r') as f1:
ITload = []
for line1 in f1:
ITload.append(line1)
f1.close()
with open ('DR.csv','r') as f2:
DR =[]
for line2 in f2:
DR.append(line2)
f2.close()
print ITload
print Pcooling
print DR
for i in range(1,200):
for it in range(1, 1440):
Tm = np.empty(1440)
Tm.fill(18)
TmA = np.empty(1440)
TmA.fill(27)
Phvac_flex = {}
Phvac_up = {}
Phvac_down_= {}
Phvac_up_ = {}
Pbess_out_ = {}
Pbess_in_ = {}
Phvac_down = {}
Pbess_flex_ = {}
Pbess_flex = {}
Phvac_flex_ = {}
Pbess_in = {}
Pdc = {}
Pdc_base = {}
Pflex_i = {}
Tdc_i = {}
Pbess_out ={}
Ebess_i = {}
Phvac_flex[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS,name="PHVAC_flex"+str(i))
Phvac_up[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_up" + str(i))
Phvac_up_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_up_" + str(i))
Phvac_down_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_down_" + str(i))
Pbess_out_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_out_" + str(i))
Pbess_in_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_in_" + str(i))
Phvac_down[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_down" + str(i))
Pbess_flex_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_flex_" + str(i))
Pbess_flex[i] = OPTmodel.addVar(lb=-GRB.INFINITY,ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_flex" + str(i))
Phvac_flex_[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PHVAC_flex_" + str(i))
Pbess_in[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_in" + str(i))
Pdc[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PDC" + str(i))
Pdc_base[i] = OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PDC_base" + str(i))
Pflex_i[i]= OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="Pflex_i" + str(i))
Tdc_i[i]= OPTmodel.addVar(ub=GRB.INFINITY,vtype = GRB.CONTINUOUS, name = "Tdc_i" + str(i))
Pbess_out[i] = OPTmodel.addVar(lb=-GRB.INFINITY,ub=GRB.INFINITY,vtype=GRB.CONTINUOUS, name="PBESS_out" + str(i))
Ebess_i[i]= OPTmodel.addVar(ub=GRB.INFINITY,vtype=GRB.CONTINUOUS,name="Ebess_i" + str(i))
Pflex_i[1] = 0
Pflex_i[1] = 0
Tdc_i[0] = 18
Phvac_flex[1] = 0
# Phvac_flex_[1] = 0
Phvac_down[1] = 0
Phvac_up[1] = 0
Phvac_down_[1] = 0
Phvac_up_[1] = 0
# Phvac_down_pos[1] = 0
# Phvac_up_pos(1) = 0;
Pbess_flex[1] = 0
# Pbess_flex_[1] = 0
Pbess_out[1] = 0
Pbess_in[1] = 0
# Pbess_out_[1] = 0
Pbess_in_[1] = 0
# Pbess_out_pos[1] = -250
# Pbess_in_pos(1) = 250;
Ebess_i[1] = 150
OPTmodel.update()
'''
if float(DR[i]) > 0:
Phvac_down_[i] = 0
Phvac_up_[i] = float(DR[i])
Pbess_out_[i] = 0
Pbess_in_[i] = float(DR[i])
#Pbess_flex_[i] = Pbess_in_[i] + Pbess_out_[i]
#Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
OPTmodel.update()
elif float(DR[i]) < 0:
Phvac_down_[i] = float(DR[i])
Phvac_up_[i] = 0
#Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
Pbess_out_[i] = float(DR[i])
Pbess_in_[i] = 0
#Pbess_flex_[i] = Pbess_in_[i] + Pbess_out_[i]
OPTmodel.update()
else:
Phvac_down_[i] = 0
Phvac_up_[i] = 0
Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
Pbess_out_[i] = 0
Pbess_in_[i] = 0
Pbess_flex_[i] = Pbess_in_[i] + Pbess_out_[i]
OPTmodel.update()
'''
#print Phvac_up.values()
#print Phvac_flex_[i]
print OPTmodel
OPTmodel.update()
ConHVAC1 = OPTmodel.addConstr(Phvac_flex[i] == Phvac_up[i] + Phvac_down[i], name='ConHVAC1')
ConHVAC2 = OPTmodel.addConstr(0 <= Phvac_flex[i] , name='ConHVAC2')
ConHVAC3 = OPTmodel.addConstr(Phvac_flex[i] <= PcoolingRated, name='ConHVAC3')
PH = pd.read_csv('Pcooling.csv')
PHVAC = PH.values
newList2 = map(lambda x: x / 1000, PHVAC)
p=[]
p=PcoolingRated-newList2[i]
#CONHVAC4 = OPTmodel.addConstr(Phvac_up[i]==np.minimum((Phvac_up_[i]),(float(newList2[i]))))
#Phvac_u(1:MaxIter) == min(Phvac_u_(1:MaxIter), (repelem(Phvac_max, MaxIter) - (Pcooling(1:MaxIter)'/1000)))
ConTemp1 = OPTmodel.addConstr(Tm[it] <= Tdc_i[i] <= TmA[it], name='ConTemp1')
ConBESS1 = OPTmodel.addConstr(Pbess_ratedN <= Pbess_flex[i] <= Pbess_rated, name='ConBESS1')
ConBESS2 = OPTmodel.addConstr(Pbess_flex[i] == Pbess_in[i] + Pbess_out[i], name='ConBESS2')
ConBESS3 = OPTmodel.addConstr(0 <= Pbess_in[i] <= min(Pbess_rated, Pbess_in_[i]), name='ConBESS3')
ConBESS4 = OPTmodel.addConstr(np.maximum(Pbess_ratedN,Pbess_out_[i]) <= Pbess_out[i]<=0 , name='ConBESS4') # need to modifty
ConEBESS1 = OPTmodel.addConstr(Ebess_min <= Ebess_i[i], name='ConEBESS1')
ConEBESS2 = OPTmodel.addConstr(Ebess_i[i] <= Ebess_max, name='ConEBESS2')
D = pd.read_csv('DR.csv').values
DRN = map(lambda x: x / 1000, D)
PDRN=map(lambda x: x / 4.8, DRN)
if float((PDRN[i])) > 0:
CON1 = OPTmodel.addConstr(Pbess_flex_[i] == Pbess_in_[i] + Pbess_out_[i],'CON1')
CON2 = OPTmodel.addConstr(Phvac_flex_[i] == Phvac_up_[i] + Phvac_down_[i],'CON2')
CON3=OPTmodel.addConstr(Phvac_down_[i] == 0, name='CON3')
CON4=OPTmodel.addConstr(Phvac_up_[i] == float((PDRN[i])),name='CON4')
CON5=OPTmodel.addConstr(Pbess_out_[i] == 0,name='CON5')
CON6=OPTmodel.addConstr(Pbess_in_[i] == float((PDRN[i])),name='CON6')
elif float(np.transpose(PDRN[i])) < 0:
CON7=OPTmodel.addConstr(Phvac_down_[i] == float(np.transpose(PDRN[i])),name='CON7')
CON8=OPTmodel.addConstr(Phvac_up_[i] == 0,name='CON8')
# Phvac_flex_[i] = Phvac_down_[i] + Phvac_up_[i]
CON9=OPTmodel.addConstr(Pbess_out_[i] == float((PDRN[i])),name='CON9')
CON10=OPTmodel.addConstr(Pbess_in_[i] == 0,name='CON10')
else:
CON11=OPTmodel.addConstr(Phvac_down_[i] == 0,name='CON11')
CON12=OPTmodel.addConstr(Phvac_up_[i] == 0,name='CON12')
CON13=OPTmodel.addConstr(Phvac_flex_[i] == Phvac_down_[i] + Phvac_up_[i],name='CON13')
CON14=OPTmodel.addConstr(Pbess_out_[i] == 0)
CON15=OPTmodel.addConstr(Pbess_in_[i] == 0,name='CON15')
CON16=OPTmodel.addConstr(Pbess_flex_[i] == Pbess_in_[i] + Pbess_out_[i],name='CON16')
OPTmodel.update()
ConPDC = OPTmodel.addConstr(Pdc[i] == Pflex_i[i] + float(ITload[i]), name='ConPDC')
# OPTmodel.addConstr(Tdc_i[i]==(ki*Tdc_i[i-1]+(ko*Tamb)))
#for x in Ebess_i:
#ConEBESS2 = OPTmodel.addConstr(Ebess_i[i] ==((Pbess_in[i] / 0.75) + (Pbess_out[i] * 0.75)))
cooling = np.array(pd.read_csv('Pcooling.csv'))
DRR = pd.read_csv('DR.csv')
DR = DRR.values
IT = pd.read_csv('ITpower.csv')
ITload = IT.values
newList = map(lambda x: x / 1000, ITload)
PH = pd.read_csv('Pcooling.csv')
PHVAC = PH.values
newList2 = map(lambda x: x / 1000, PHVAC)
#for y in Tdc_i:
T=pd.read_csv('TT.csv').values
OPTmodel.addConstr(Tdc_i[i]==((ki*float(T[i]))+(ko*Tamb)+(kc*float(newList[i]))-((kp*(float(newList2[i])))+(Phvac_flex[i]*3.14))))
print Tdc_i.values()
OPTmodel.addConstr(Pbess_out_[i]<=Phvac_flex[i] + Pbess_flex[i]<=Pbess_in_[i])
# Tdc_i[1:len(i)]==(Ki*Tdc_i[1:1438])+(Kc*array2[1:1438])+(Ko*Tamb))
ConBESS5 = OPTmodel.addConstr(Pbess_flex[i] == Pbess_in[i] + Pbess_out[i], name='ConBESS5')
#OPTmodel.addConstr(defIT[i]==DeferableLoad.j2 + DeferableLoad.j3)
# OPTmodel.addConstr(Pdc_base[i]==predictions[i])
ConFLEX = OPTmodel.addConstr(Pflex_i[i] == Pbess_flex[i] + Phvac_flex[i], name='ConFLEX')
PcoolingPredicted = pd.read_csv('PcoolingPredictionResult.csv')
PcoolingPredictedValue = PcoolingPredicted.values
ITPredicted = pd.read_csv('ITpredictionResult.csv')
ITPredictedValue = ITPredicted.values
ConPDCbase = OPTmodel.addConstr(Pdc_base[i] == np.transpose(ITPredictedValue[i]) + np.transpose(PcoolingPredictedValue[i]))
OPTmodel.update()
# OPTmodel.addConstr(Pdc_base[i]==prediction[i])
OPTmodel.setObjective((np.transpose(Pdc_base[i])-float(DR[i]) - (Pdc[i]) ), GRB.MINIMIZE)
OPTmodel.update()
OPTmodel.optimize()
print Pdc_base[i].X
#print Ebess_i[i].X
#print Phvac_flex[i].X
print Tdc_i[i]
print Pdc[i]
print Phvac_flex[i]
print Pbess_flex[i]
print Pbess_out[i]
print Pbess_in[i]
print Ebess_i[i]
print Pbess_flex_[i]
print Phvac_down[i]
print Phvac_up[i]
'''
def get_results(self):
"""
This function gets the results of the current optimization model
Returns
-------
"""
HVACresult = np.zeros(1,N)
BatteryResult = np.zeros(1,N)
SOC = np.zeros(1,N)
#r_Q_dot = np.zeros((self.gp.N_H, self.N_S))
#r_P = np.zeros((self.gp.N_H, self.N_S))
#r_P_self = np.zeros((self.gp.N_H, self.N_S))
#r_P_ex = np.zeros((self.gp.N_H, self.N_S))
#r_Q_dot_gas = np.zeros((self.gp.N_H, self.N_S))
#Load = np.zeros((self.gp.N_H, self.N_S))
try:
for t in range(1,N):
HVACresult[t]= Phvac_flex[t].X
BatteryResult[t]=Pbess_flex[t].X
SOC[t] = Ebess_i[t].X / Ebess_max
except:
pass
return { 'SOC' : SOC , 'BatteryResult': BatteryResult }
print OPTmodel.getVars()
# get results
Temp = {}
Battery = {}
Ebess_result = {}
ITloadd = {}
for t in range(1,N):
Temp[t] = OPTmodel.getVarByName("Tdc_i" )
Battery[t] = OPTmodel.getVarByName("PBESS_flex" )
Ebess_result[t] = OPTmodel.getVarByName("Ebess_i" )
#r_P_e[t] = model.getVarByName("P_export_%s_0" % t).X
fig, axes = plt.subplots(4, 1)
# plot elctricity
ax5 = axes[2]
ax6 = ax5.twinx()
ax5.plot( [Temp[t] for t in range(1,N)], 'g-')
ax6.plot([Ebess_result[t] for t in range(1,N)], 'b-')
ax5.set_xlabel('Time index')
ax5.set_ylabel('Power Import [W]', color='g')
ax6.set_ylabel('Power CHP [W]', color='b')
ax7 = axes[3]
ax7.plot([Battery[t] for t in range(1,N)], 'g-')
ax7.set_ylabel('Power Export [W]', color='g')
'''
print Pflex_i.values()
# print OPTmodel.getVars()
print OPTmodel.feasibility()
print OPTmodel.getObjective()
print Pdc_base.values()
'''
b = map(float, Phvac_flex)
plt.plot(b)
plt.show()
'''
#c = map(float, Pbess_flex_)
#plt.plot(c)
#plt.show()
print OPTmodel
print Tdc_i.values()
# get results
print OPTmodel.getVars()
# print OPTmodel.getAttr('EBESS_i')
status = OPTmodel.status
print status
# print Con10,Con12
print Phvac_flex.values()
print Pbess_flex.values()
print Ebess_i.values()
print OPTmodel.objval
print Tdc_i
print Pbess_in
print Pbess_out.values()
# print Pbess_flex
# print Phvac_flex
# print Ebess_i
print Pflex_i.values()
print Pbess_flex_.values()
#print OPTmodel.getVars()
print OPTmodel.feasibility()
print OPTmodel.getObjective()
print Ebess_i.values()
if OPTmodel.status == GRB.Status.INF_OR_UNBD:
# Turn presolve off to determine whether model is infeasible
# or unbounded
OPTmodel.setParam(GRB.Param.Presolve, 0)
OPTmodel.optimize()
OPTmodel.write("mymodel.lp")
if OPTmodel.status == GRB.Status.OPTIMAL:
print('Optimal objective: %g' % OPTmodel.objVal)
OPTmodel.write('model.sol')
exit(0)
elif OPTmodel.status != GRB.Status.INFEASIBLE:
print('Optimization was stopped with status %d' % OPTmodel.status)
exit(0)
# Model is infeasible - compute an Irreducible Inconsistent Subsystem (IIS)
print('')
print('Model is infeasible')
OPTmodel.computeIIS()
OPTmodel.write("model.ilp")
print("IIS written to file 'model.ilp'")
I want to plot the computed values from gurobi but when I want to get the X attribute of gurobi variable it says that AttributeError: it has no attribute 'X' and the when I cast the value from float to int it just showed me the empty plot but at the lp file I could see the result of each iteration
I am anxiously waiting for your response
cherrs

If / else statement not working depending on random number (Python)

I'm making a text encrypt-er that randomizes the pattern of symbols used (abcd) but after the first if statement, the program no longer works. New, old, get , and tag are the 4 letter to symbol translations. I tested out only the first if statement by itself and it worked perfectly fine. Also any tips in how to shorten the code would be much appreciated.
our_str = input("Mornin' ")
length = (len(our_str)/2)
rounded = round(length)
import random
rand = random.randint(1,6)
print(rand)
if rand <= 2: #abcd
new_str = our_str[:rounded].replace('a', ']')
new1_str = new_str.replace('b', '◙')
new2_str = new1_str.replace('c', '♂')
new3_str = new2_str.replace('d', 'd')
new4_str = new3_str.replace('e', 'e')
new5_str = new4_str.replace('f', '▓')
new6_str = new5_str.replace('g', '─')
new7_str = new6_str.replace('h', 'Φ')
new8_str = new7_str.replace('i', 'Θ')
new9_str = new8_str.replace('j', '≥')
new10_str = new9_str.replace('k', '≤')
new11_str = new10_str.replace('l', 'L')
new12_str = new11_str.replace('m', 'M')
new13_str = new12_str.replace('n', 'V')
new14_str = new13_str.replace('o', 'W')
new15_str = new14_str.replace('p', '►')
new16_str = new15_str.replace('q', '◄')
new17_str = new16_str.replace('r', '→')
new18_str = new17_str.replace('s', '←')
new19_str = new18_str.replace('t', 't')
new20_str = new19_str.replace('u', 'u')
new21_str = new20_str.replace('v', '~')
new22_str = new21_str.replace('w', '⌂')
new23_str = new22_str.replace('x', '°')
new24_str = new23_str.replace('y', '∙')
new25_str = new24_str.replace('z', '☻')
new26_str = new25_str.replace(' ', 'f')
old_str = our_str[rounded:2 * rounded].replace('a', 'Y')
old1_str = old_str.replace('b', 'É')
old2_str = old1_str.replace('c', 'Θ')
old3_str = old2_str.replace('d', '╩')
old4_str = old3_str.replace('e', 'b')
old5_str = old4_str.replace('f', '█')
old6_str = old5_str.replace('g', '=')
old7_str = old6_str.replace('h', '↑')
old8_str = old7_str.replace('i', 'U')
old9_str = old8_str.replace('j', '⌂')
old10_str = old9_str.replace('k', '┬')
old11_str = old10_str.replace('l', 'æ')
old12_str = old11_str.replace('m', '◄')
old13_str = old12_str.replace('n', '1')
old14_str = old13_str.replace('o', 'B')
old15_str = old14_str.replace('p', 'Ñ')
old16_str = old15_str.replace('q', '╡')
old17_str = old16_str.replace('r', '▌')
old18_str = old17_str.replace('s', '♣')
old19_str = old18_str.replace('t', 'Γ')
old20_str = old19_str.replace('u', 'τ')
old21_str = old20_str.replace('v', '╔')
old22_str = old21_str.replace('w', '░')
old23_str = old22_str.replace('x', '┘')
old24_str = old23_str.replace('y', 'ó')
old25_str = old24_str.replace('z', ';')
old26_str = old25_str.replace(' ', 'ß')
get_str = our_str[2 * rounded:3 * rounded].replace('a', 'ç')
get1_str = get_str.replace('b', '1')
get2_str = get1_str.replace('c', '♣')
get3_str = get2_str.replace('d', 'ⁿ')
get4_str = get3_str.replace('e', '♠')
get5_str = get4_str.replace('f', 'S')
get6_str = get5_str.replace('g', '°')
get7_str = get6_str.replace('h', '♫')
get8_str = get7_str.replace('i', 'D')
get9_str = get8_str.replace('j', '│')
get10_str = get9_str.replace('k', '←')
get11_str = get10_str.replace('l', 'ƒ')
get12_str = get11_str.replace('m', 'Æ')
get13_str = get12_str.replace('n', 'P')
get14_str = get13_str.replace('o', '#') #skipped 0781, 6406
get15_str = get14_str.replace('p', '.') #0899
get16_str = get15_str.replace('q', '┤') #0348
get17_str = get16_str.replace('r', 'µ')
get18_str = get17_str.replace('s', 'E')
get19_str = get19_str.replace('t', '§')
get20_str = get20_str.replace('u', '▬')
get21_str = get21_str.replace('v', 'û')
get22_str = get22_str.replace('w', '♀')
get23_str = get23_str.replace('x', '&')
get24_str = get24_str.replace('y', '≈')
get25_str = get25_str.replace('z', 'ª') #4460
get26_str = get26_str.replace(' ', 'N')
tag_str = our_str[3 * rounded:].replace('a', '╬')
tag1_str = tag_str.replace('b', '↓')
tag2_str = tag1_str.replace('c', '<')
tag3_str = tag2_str.replace('d', '╦')
tag4_str = tag3_str.replace('e', '-')
tag5_str = tag4_str.replace('f', 'δ') #skipped 360
tag6_str = tag5_str.replace('g', '▼')
tag7_str = tag6_str.replace('h', '╫')
tag8_str = tag7_str.replace('i', '`')
tag9_str = tag8_str.replace('j', 'û')
tag10_str = tag9_str.replace('k', '±')
tag11_str = tag10_str.replace('l', '⌡')
tag12_str = tag11_str.replace('m', '≈')
tag13_str = tag12_str.replace('n', ']')
tag14_str = tag13_str.replace('o', '╗')
tag15_str = tag14_str.replace('p', '┐')
tag16_str = tag15_str.replace('q', '>')
tag17_str = tag16_str.replace('r', '╞')
tag18_str = tag17_str.replace('s', '╟') #627
tag19_str = tag18_str.replace('t', '╘')
tag20_str = tag19_str.replace('u', 'L')
tag21_str = tag20_str.replace('v', 'v') #353
tag22_str = tag21_str.replace('w', '#')
tag23_str = tag22_str.replace('x', 'R')
tag24_str = tag23_str.replace('y', ';')
tag25_str = tag24_str.replace('z', '~')
tag26_str = tag25_str.replace(' ', '▓')
print(new26_str + old26_str + get26_str + tag26_str)
elif 2 < rand <= 4 #abdc
new_str = our_str[:rounded].replace('a', ']')
new1_str = new_str.replace('b', '◙')
new2_str = new1_str.replace('c', '♂')
new3_str = new2_str.replace('d', 'd')
new4_str = new3_str.replace('e', 'e')
new5_str = new4_str.replace('f', '▓')
new6_str = new5_str.replace('g', '─')
new7_str = new6_str.replace('h', 'Φ')
new8_str = new7_str.replace('i', 'Θ')
new9_str = new8_str.replace('j', '≥')
new10_str = new9_str.replace('k', '≤')
new11_str = new10_str.replace('l', 'L')
new12_str = new11_str.replace('m', 'M')
new13_str = new12_str.replace('n', 'V')
new14_str = new13_str.replace('o', 'W')
new15_str = new14_str.replace('p', '►')
new16_str = new15_str.replace('q', '◄')
new17_str = new16_str.replace('r', '→')
new18_str = new17_str.replace('s', '←')
new19_str = new18_str.replace('t', 't')
new20_str = new19_str.replace('u', 'u')
new21_str = new20_str.replace('v', '~')
new22_str = new21_str.replace('w', '⌂')
new23_str = new22_str.replace('x', '°')
new24_str = new23_str.replace('y', '∙')
new25_str = new24_str.replace('z', '☻')
new26_str = new25_str.replace(' ', 'f')
old_str = our_str[rounded:2 * rounded].replace('a', 'Y')
old1_str = old_str.replace('b', 'É')
old2_str = old1_str.replace('c', 'Θ')
old3_str = old2_str.replace('d', '╩')
old4_str = old3_str.replace('e', 'b')
old5_str = old4_str.replace('f', '█')
old6_str = old5_str.replace('g', '=')
old7_str = old6_str.replace('h', '↑')
old8_str = old7_str.replace('i', 'U')
old9_str = old8_str.replace('j', '⌂')
old10_str = old9_str.replace('k', '┬')
old11_str = old10_str.replace('l', 'æ')
old12_str = old11_str.replace('m', '◄')
old13_str = old12_str.replace('n', '1')
old14_str = old13_str.replace('o', 'B')
old15_str = old14_str.replace('p', 'Ñ')
old16_str = old15_str.replace('q', '╡')
old17_str = old16_str.replace('r', '▌')
old18_str = old17_str.replace('s', '♣')
old19_str = old18_str.replace('t', 'Γ')
old20_str = old19_str.replace('u', 'τ')
old21_str = old20_str.replace('v', '╔')
old22_str = old21_str.replace('w', '░')
old23_str = old22_str.replace('x', '┘')
old24_str = old23_str.replace('y', 'ó')
old25_str = old24_str.replace('z', ';')
old26_str = old25_str.replace(' ', 'ß')
get_str = our_str[3 * rounded:].replace('a', 'ç')
get1_str = get_str.replace('b', '1')
get2_str = get1_str.replace('c', '♣')
get3_str = get2_str.replace('d', 'ⁿ')
get4_str = get3_str.replace('e', '♠')
get5_str = get4_str.replace('f', 'S')
get6_str = get5_str.replace('g', '°')
get7_str = get6_str.replace('h', '♫')
get8_str = get7_str.replace('i', 'D')
get9_str = get8_str.replace('j', '│')
get10_str = get9_str.replace('k', '←')
get11_str = get10_str.replace('l', 'ƒ')
get12_str = get11_str.replace('m', 'Æ')
get13_str = get12_str.replace('n', 'P')
get14_str = get13_str.replace('o', '#') #skipped 0781, 6406
get15_str = get14_str.replace('p', '.') #0899
get16_str = get15_str.replace('q', '┤') #0348
get17_str = get16_str.replace('r', 'µ')
get18_str = get17_str.replace('s', 'E')
get19_str = get19_str.replace('t', '§')
get20_str = get20_str.replace('u', '▬')
get21_str = get21_str.replace('v', 'û')
get22_str = get22_str.replace('w', '♀')
get23_str = get23_str.replace('x', '&')
get24_str = get24_str.replace('y', '≈')
get25_str = get25_str.replace('z', 'ª') #4460
get26_str = get26_str.replace(' ', 'N')
tag_str = our_str[2 * rounded: 3 * rounded].replace('a', '╬')
tag1_str = tag_str.replace('b', '↓')
tag2_str = tag1_str.replace('c', '<')
tag3_str = tag2_str.replace('d', '╦')
tag4_str = tag3_str.replace('e', '-')
tag5_str = tag4_str.replace('f', 'δ') #skipped 360
tag6_str = tag5_str.replace('g', '▼')
tag7_str = tag6_str.replace('h', '╫')
tag8_str = tag7_str.replace('i', '`')
tag9_str = tag8_str.replace('j', 'û')
tag10_str = tag9_str.replace('k', '±')
tag11_str = tag10_str.replace('l', '⌡')
tag12_str = tag11_str.replace('m', '≈')
tag13_str = tag12_str.replace('n', ']')
tag14_str = tag13_str.replace('o', '╗')
tag15_str = tag14_str.replace('p', '┐')
tag16_str = tag15_str.replace('q', '>')
tag17_str = tag16_str.replace('r', '╞')
tag18_str = tag17_str.replace('s', '╟') #627
tag19_str = tag18_str.replace('t', '╘')
tag20_str = tag19_str.replace('u', 'L')
tag21_str = tag20_str.replace('v', 'v') #353
tag22_str = tag21_str.replace('w', '#')
tag23_str = tag22_str.replace('x', 'R')
tag24_str = tag23_str.replace('y', ';')
tag25_str = tag24_str.replace('z', '~')
tag26_str = tag25_str.replace(' ', '▓')
print(new26_str + old26_str + tag26_str + get26_str)
hi = input("Bye")
P.S - The hi input is to not let the Python console close.
1st Error: You have used variables in following statements without initializing them first
get19_str = get19_str.replace('t', '§')
get20_str = get20_str.replace('u', '▬')
get21_str = get21_str.replace('v', 'û')
get22_str = get22_str.replace('w', '♀')
get23_str = get23_str.replace('x', '&')
get24_str = get24_str.replace('y', '≈')
get25_str = get25_str.replace('z', 'ª') #4460
get26_str = get26_str.replace(' ', 'N')
2nd Error: If statements do not allow two relational operations to be performed on a single variable without using a logical operator for joining the two (in case of n relational operations you should use n-1 logical operators to combine them all)
Eg. Check if integer a is greater than 2 and less than 5
if (a>2) and (a<5):
#statements
So you will have to change your elif statement by seperating the two re
Try this:
elif ((rand > 2) and (rand <= 4)):
# Do your stuff here
Doing what you did will compare 2 to the expression (rand <= 4), which compares to a boolean, or 0/1.
The very first line: our_str = input("Mornin' ")
our_str should be converted to integer.
Your conditionals are not right.
elif 2 < rand <= 4: it doesn't work this way.
instead use elif rand in [3,4]: or elif rand > 2 and rand <= 4:
There are other errors as well, you can check the console and remove all the errors.
like you are using get19_str without even initialising it and so on...

Categories

Resources