I want to create a filepath using a variable i want to do it like this
import os
import gettitle as gt
def convert_file(
oldfilelocation = 'C:/Muziek' + (gt.finalyoutubetitle) + '.m4a'
newfilefilelocation = 'C:/Muziek' + (gt.finalyoutubetitle) + '.mmp3'
os.rename(r(oldfilelocation),r(newfilelocation))
)
exit()
But if i do this is get a lot of errors shown below.
The correct syntax is
2 method parameters oldfilelocation and newfilelocation, with default value
1 statement
def convert_file(oldfilelocation='C:/Muziek' + (gt.finalyoutubetitle) + '.m4a',
newfilelocation='C:/Muziek' + (gt.finalyoutubetitle) + '.mmp3'):
os.rename(oldfilelocation, newfilelocation)
Original issue is now resolved, many thanks to eryksun.
Fixed code is below, I now have a different issue that I will ask about in another thread if I cannot figure it out.
Error 6 is invalid handle, however, the handle appears to be good, I believe the error is coming from the second parameter.
status = advapi32.SetServiceStatus(g_hServiceStatus, pointer(m_oServiceStatus))
if 0 == status:
dwStatus = winKernel.GetLastError()
Note: if I make the pointer None, then it doesn't fail (but obviously doesn't do anything useful either).
python -V
Python 3.6.6
Larger snippet:
from ctypes import *
from ctypes.wintypes import *
winKernel = ctypes.WinDLL('kernel32', use_last_error=True)
advapi32 = ctypes.WinDLL('advapi32', use_last_error=True)
global g_ServiceName
g_ServiceName = "StatusMonitor"
global g_lpcstrServiceName
g_lpcstrServiceName = LPCSTR(b"StatusMonitor")
class _SERVICE_STATUS(Structure):
_pack_ = 4
_fields_ = [
("dwServiceType", DWORD),
("dwCurrentState", DWORD),
("dwControlsAccepted", DWORD),
("dwWin32ExitCode", DWORD),
("dwServiceSpecificExitCode", DWORD),
("dwCheckPoint", DWORD),
("dwWaitHint", DWORD)
]
LPSERVICE_STATUS = POINTER(_SERVICE_STATUS)
global m_oServiceStatus
m_oServiceStatus = _SERVICE_STATUS(0, 0, 0, 0, 0, 0, 0)
global g_hServiceStatus
g_hServiceStatus = SERVICE_STATUS_HANDLE(None)
<lots of code snipped>
def status_report(dwCurrentState, dwWin32ExitCode, dwWaitHint):
global g_dwCheckPoint
global g_isService
try:
# Fill in the SERVICE_STATUS structure.
m_oServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS
m_oServiceStatus.dwCurrentState = dwCurrentState
m_oServiceStatus.dwWin32ExitCode = dwWin32ExitCode
m_oServiceStatus.dwWaitHint = dwWaitHint
if dwCurrentState == SERVICE_START_PENDING:
m_oServiceStatus.dwControlsAccepted = 0
else:
m_oServiceStatus.dwControlsAccepted = 1
if (dwCurrentState == SERVICE_STOPPED) or (dwCurrentState == SERVICE_RUNNING):
m_oServiceStatus.dwCheckPoint = 0
else:
g_dwCheckPoint += 1
m_oServiceStatus.dwCheckPoint = g_dwCheckPoint
status = advapi32.SetServiceStatus(g_hServiceStatus, pointer(m_oServiceStatus))
if 0 == status:
dwStatus = winKernel.GetLastError()
#logging.info("SetServiceStatus(" + str(g_hServiceStatus) + ", status=" + str(dwStatus) + ")")
logging.info("status_report(" + str(g_hServiceStatus) + ", " + str(dwCurrentState) + ", " + str(dwWin32ExitCode) + ", " + str(dwWaitHint) + ")")
dwStatus = None
if g_isService:
# Report the status of the service to the SCM.
ptrServiceStatus = LPSERVICE_STATUS(m_oServiceStatus)
logging.info("m_oServiceStatus struct: " + str(m_oServiceStatus) + ", ref: " + str(byref(m_oServiceStatus)))
logging.info(" " + "ptr: " + str(str(pointer(m_oServiceStatus))) + " PTR: " + str(ptrServiceStatus))
advapi32.SetServiceStatus.restype = BOOL
advapi32.SetServiceStatus.argtypes = [SERVICE_STATUS_HANDLE, LPSERVICE_STATUS]
status = advapi32.SetServiceStatus(g_hServiceStatus, ptrServiceStatus)
if 0 == status:
dwStatus = ctypes.get_last_error()
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
logging.error("status_report " + str(e) + " line: " + str(exc_tb.tb_lineno))
return dwStatus
advapi32.RegisterServiceCtrlHandlerExA.restype = SERVICE_STATUS_HANDLE
advapi32.RegisterServiceCtrlHandlerExA.argtypes = [LPCSTR, LPHANDLER_FUNCTION_EX, LPVOID]
g_hServiceStatus = advapi32.RegisterServiceCtrlHandlerExA(g_lpcstrServiceName, LPHANDLER_FUNCTION_EX(svc_control_handler_ex), LPVOID(None))
logging.info("control handler " + str(g_hServiceStatus))
logging.info("control handler called count " + str(g_nServiceControlHandlerCalled))
m_oServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
m_oServiceStatus.dwServiceSpecificExitCode = 0;
# set the service state as pending
dwStatus = status_report(SERVICE_START_PENDING, NO_ERROR, 3000);
logging.info("service_main: status_report(" + str(g_hServiceStatus) + "), status=" + str(dwStatus))
log_service_status(m_oServiceStatus)
Updated logging result:
INFO service_start
INFO service_start: StopEventHandle 952
INFO service_main called JimsStatusMonitor control handler called count 0
INFO control handler 2787686645712
INFO control handler called count 0
INFO status_report(2787686645712, 2, 0, 3000)128
INFO m_oServiceStatus struct: <__main__._SERVICE_STATUS object at 0x000002890FC666C8>, ref: <cparam 'P' (000002890FCA8A30)>
INFO ptr: <__main__.LP__SERVICE_STATUS object at 0x000002890FC66848> PTR: <__main__.LP__SERVICE_STATUS object at 0x000002890FC66648>
INFO service_main: status_report(2787686645712), status=None
INFO 16, 2, 0, 0, 0, 1, 3000
I must be missing something obvious, but I don't see it. I tried different pack to the structure, but with no improvement.
I also tried using byref() instead of pointer() and just passing the structure, but none of those worked. I believe using pointer() is correct here because there is another API to set the dispatch table that is working using pointer().
Note that I am specifically using FFI for this as I found the existing packages lacking for what I am trying to do. This Python solution is based on a C++ solution that I wrote that works, I just need to understand whatever nuance to the FFI that is causing it to fail.
I should add that the service is actually running at this point, I just can't transition it out of Starting state with this issue.
Hopefully someone can tell me what I am doing wrong?
Thanks in advance,
-Dave
With many thanks to eryksun, I was able to resolve the original issue.
The main issue was that I was assuming the Windows APIs were fully defined because it seemed like they were working without restype and argstype defined.
Needed the following:
advapi32.RegisterServiceCtrlHandlerExA.restype = SERVICE_STATUS_HANDLE
advapi32.RegisterServiceCtrlHandlerExA.argtypes = [LPCSTR, LPHANDLER_FUNCTION_EX, LPVOID]
g_hServiceStatus = advapi32.RegisterServiceCtrlHandlerExA(g_lpcstrServiceName, LPHANDLER_FUNCTION_EX(svc_control_handler_ex), LPVOID(None))
advapi32.SetServiceStatus.restype = BOOL
advapi32.SetServiceStatus.argtypes = [SERVICE_STATUS_HANDLE, LPSERVICE_STATUS]
status = advapi32.SetServiceStatus(g_hServiceStatus, ptrServiceStatus)
With those defined correctly, there were still two remaining issues that I was able to figure out from the documentation.
The first was I missed that restype is the first argument to WINFUNCTYPE(), given the responses from eryksun, it was more obvious to me, and that explained why my definition for my service_main() wasn't working as expected.
The second was a bit more subtle and is found at the end of the callback documentation here:
Important note for callback functions:
Make sure you keep references to CFUNCTYPE objects as long as they are
used from C code. ctypes doesn't, and if you don't, they may be
garbage collected, crashing your program when a callback is made.
Note that the original code that was failing can be found in the Python forum here.
I'm faced with a really ugly code that is a code generator, that takes a configuration file and outputs C code.
It works, but the script is full of things like:
outstr = "if(" + mytype + " == " + otherType + "){\n"
outstr += " call_" + fun_for_type(mytype) + "();\n"
outstr += "}\n"
# Now imagine 1000 times more lines like the previous ones...
Is there a tool to automatically change code like that to something more palatable (partial changes are more than welcome)? Like:
outstr = """if ({type} == {otherType}) {
call_{fun_for_type}({type});
}
""".format(type=mytype, otherType=otherType, fun_for_type=(mytype))
If this would have been C then I would have abused of Coccinelle, but I don't know of similar tools for Python.
Thanks
You can use dictionaries :
datas = {"type":mytype, "otherType":otherType, "fun_for_type":(mytype)}
outstr = "if ({type} == {otherType}) {{\n\
call_{fun_for_type}({type});\n\
}}\n".format(**datas)
I am using the following code to process a list of images that is found in my scene, before the gathered information, namely the tifPath and texPath is used in another function.
However, example in my scene, there are 3 textures, and hence I should be seeing 3 sets of tifPath and texPath but I am only seeing 1 of them., whereas if I am running to check surShaderOut or surShaderTex I am able to see all the 3 textures info.
For example, the 3 textures file path is as follows (in the surShaderTex): /user_data/testShader/textureTGA_01.tga, /user_data/testShader/textureTGA_02.tga, /user_data/testShader/textureTGA_03.tga
I guess what I am trying to say is that why in my for statement, it is able to print out all the 3 results and yet anything bypass that, it is only printing out a single result.
Any advices?
surShader = cmds.ls(type = 'surfaceShader')
for con in surShader:
surShaderOut = cmds.listConnections('%s.outColor' % con)
surShaderTex = cmds.getAttr("%s.fileTextureName" % surShaderOut[0])
path = os.path.dirname(surShaderTex)
f = surShaderTex.split("/")[-1]
tifName = os.path.splitext(f)[0] + ".tif"
texName = os.path.splitext(f)[0] + ".tex"
tifPath = os.path.join(path, tifName)
texPath = os.path.join(path, texName)
convertText(surShaderTex, tifPath, texPath)
Only two lines are part of your for loop. The rest only execute once.
So first this runs:
surShader = cmds.ls(type = 'surfaceShader')
for con in surShader:
surShaderOut = cmds.listConnections('%s.outColor' % con)
surShaderTex = cmds.getAttr("%s.fileTextureName" % surShaderOut[0])
Then after that loop, with only one surShader, one surShaderOut, and one surShaderTex, the following is executed once:
path = os.path.dirname(surShaderTex)
f = surShaderTex.split("/")[-1]
tifName = os.path.splitext(f)[0] + ".tif"
texName = os.path.splitext(f)[0] + ".tex"
tifPath = os.path.join(path, tifName)
texPath = os.path.join(path, texName)
Indent that the same as the lines above it, and it'll be run for each element of surShader instead of only once.
I have written a python script that creates render layers in Maya for the lighters. The script creates the 4 basic layers as shown in the picture below. The script also changes the render settings on each layer.
I got the following error while trying to change the status of render elements for chrShadow and occ layers.
# RuntimeError: # Error occurred during execution of MEL script
file: C:/Program Files/Autodesk/Maya2013/vray/scripts/vrayCreateRenderElementsTab.mel line 453: Object 'listAdded' not found.
After creating each layer, the script changes the render settings accordingly. FOllwoing is the code where it tries to change the render elements.
mel.eval("unifiedRenderGlobalsWindow")
render_elements = cmds.ls(type="VRayRenderElement")
if "Beauty" in current_layer:
for passes in render_elements:
mel.eval("listAddedPressed " + str(passes) + " 1")
elif "Shadow" in current_layer:
for passes in render_elements:
if "Shadow" in passes:
mel.eval("listAddedPressed " + str(passes) + " 1")
else:
mel.eval("listAddedPressed " + str(passes) + " 0")
elif "occ" in current_layer:
for passes in render_elements:
if "vrayRE_Extra_Tex" in passes:
mel.eval("listAddedPressed " + str(passes) + " 1")
elif "vrayRE_Velocity" in passes:
mel.eval("listAddedPressed " + str(passes) + " 1")
else:
mel.eval("listAddedPressed " + str(passes) + " 0")
For chrShadow layer the following setting is required: and for occ layer follwoing setting is required: .
If I just run this code separately later it works sometimes but mostly I get this error. Is there a way to get rid of this error?
You have to use 'evalDeferred()' command.
Maya doesn't refresh and can't change parameters in passes you just have created.
example :
> cmds.createNode( 'renderPass', name='ZDepth' )
> cmds.evalDeferred("""cmds.setRenderPassType( 'ZDepth', type='CAMZ'
> )""")