Search code examples
shared-librariesargvpython-c-apimaple

Argc and argv for external program calling C shared library


I'm trying to use Maple to call a C shared library which calls Python. Usually I need to set argc and argv in main, but since this is another program (Maple) calling the shared library, I don't have the main function (or should I have one?). Then how should I set the argc and argv?

This is the error I got:

Traceback (most recent call last):
  File "/home/shiningsun/maple/rhf.py", line 9, in function
    mol.build()
  File "/share/apps/pyscf/v11/pyscf/gto/mole.py", line 1638, in build
    return self.build_(*args, **kwargs)
  File "/share/apps/pyscf/v11/pyscf/gto/mole.py", line 1533, in build_
    _update_from_cmdargs_(self)
  File "/share/apps/pyscf/v11/pyscf/gto/mole.py", line 2297, in _update_from_cmdargs_
    opts = cmd_args.cmd_args()
  File "/share/apps/pyscf/v11/pyscf/gto/cmd_args.py", line 25, in cmd_args
    (opts, args_left) = parser.parse_args()
  File "/share/apps/anaconda2/lib/python2.7/optparse.py", line 1382, in parse_args
    rargs = self._get_args(args)
  File "/share/apps/anaconda2/lib/python2.7/optparse.py", line 1364, in _get_args
    return sys.argv[1:]
AttributeError: 'module' object has no attribute 'argv'

Solution

  • The cmd_args module only parses verbose, quiet, output and max-memory arguments. Assuming only output is relevant for you, you could set the values with PySys_SetArgv just after Py_Initialize().

    char **argv = {"", "-o", "path/to/output/file"};
    PySys_SetArgv(3, argv);