Search code examples
python-3.6

Why the imported PowerFactory module in python can only execute single time?


The script is be able to run a software called PoiwerFctory externally by Python as follows:

#add powerfactory.pyd path to python path
import sys
sys.path.append("C:\\Program Files\\DIgSILENT\\PowerFactory 2017 
SP2\\Python\\3.6")

#import powerfactory module
import powerfactory

#start powerfactory module in unattended mode (engine mode)
app=powerfactory.GetApplication()

#get the user
user=app.GetCurrentUser()

#active project
project=app.ActivateProject('Python Test') #active project "Python Test"
prj=app.GetActiveProject   #returns the actived project

#run python code below
ldf=app.GetFromStudyCase('ComLdf') #caling loadflow command object
ldf.Execute() #executing the load flow command

#get the list of lines contained in the project
Lines=app.GetCalcRelevantObjects('*.ElmLne') #returns all relevant objects, 
                                               i.e. all lines
for line in Lines: #get each element out of list
    name=line.loc_name #get name of the line
    value=line.GetAttribute('c:loading') # return the value of elements

#Print the results                     
print('Loading of the line: %s = %.2f'%(name,value))

When the above code first time executed in Spyder, it will show proper resutls. However, if re-executing the script again, the following error is appeared:

Reloaded modules: powerfactory
Traceback (most recent call last):

  File "<ipython-input-9-ae989570f05f>", line 1, in <module>
runfile('C:/Users/zd1n14/Desktop/Python Test/Call Digsilent in 
Python.py', wdir='C:/Users/zd1n14/Desktop/Python Test')

  File "C:\ProgramData\Anaconda3\lib\site-
packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-
packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/zd1n14/Desktop/Python Test/Call Digsilent in Python.py", 
line 12, in <module>
user=app.GetCurrentUser()

RuntimeError: 'powerfactory.Application' already deleted 

Referred to How can I exit powerfactory using Python in Unattended mode?, this may because of PowerFactory in still running. And the only way which has been found so far is to re-start the Spyder and execute the script again, this is so inefficiency that if I want to re-write the code and debugging it.

It would be so much appropriated that if anyone could give me some advice for such problem.


Solution

  • I ran into the same Problem. Python is still connected to powerfactory and gives the Error if you try to connect again. What basicly worked for me was to kill the instance on the end of your skript with

    del app
    

    another idea during debugging could be:

    try:
        # Do something in your skript
    finally:
        del app
    

    So the killing of the instance happens in any case.