Using conda install within a python script

2019-03-18 18:14发布

According to this answer you can import pip from within a Python script and use it to install a module. Is it possible to do this with conda install?

The conda documentation only shows examples from the command line but I'm looking for code that can be executed from within a Python script.

Yes, I could execute shell commands from within the script but I am trying to avoid this as it is basically assuming that conda cannot be imported and its functions called.

2条回答
萌系小妹纸
2楼-- · 2019-03-18 18:33

You can use conda.cli.main. For example, this installs numpy:

import conda.cli

conda.cli.main('conda', 'install',  '-y', 'numpy')

Use the -y argument to avoid interactive questions:

-y, --yes Do not ask for confirmation.

查看更多
趁早两清
3楼-- · 2019-03-18 18:35

Try this:

!conda install xyzpackage

Please remember this has to be done within the Python script not the OS prompt.

Or else you could try the following:

import sys from conda.cli import main

sys.exit(main())

try:
    import conda
    from conda.cli import main
    sys.argv = ['conda'] + list(args)
    main()
查看更多
登录 后发表回答