Access portal object from command line script

Hi!! I am writing a CLI script in a plone5 addon and want to access the portal object from the script function by including

portal = api.portal.get()

I get

plone.api.exc.CannotGetPortalError: Unable to get the portal object

error when running bin/script_name.
What am I missing?

When you take a look at the code for plone.api.portal.get(), you can see that the site is retrieved with getSite(). Trying to call getSite() from a command line script will fail (initially). How does your script know which site in your instance to use?

Take a look at how it's done in Products.CMFPlone:

First, there is a command line argument for the site id to choose: This is then used to actively set the current site: Once that is done you should be able to work with your site and use plone.api methods.

1 Like

for setSite, the example uses 'app'(bound to the top-level Zope object) . When calling the script as bin/script_name, I get "NameError: global name 'app' is not defined" error. How to access 'app' from script function?

@jensens that might be good if your experience could be shared. The specific problem in this context os, that if you run a commandline script you need to access the Zope Instance and ensure that it runs / or that you could access the ZODB and do everything.

It is a bit like ipzope script or the instance script itself.

@pavithirakc at the moment you might do have a CLI script that could do something in Python but cloud not access anything inside a running Zope Instance.

1 Like

I was trying to convert the path from zope root (passed as string argument to the script), into corresponding context (by using restrictedTraverse), to be passed into another util function. Is there any other way of doing it?

I think I just saw something about this. Maybe bin/ -O Plone where Plone is the site ID?

1 Like