我可以在Python脚本中使用pip安装模块吗?[副本]

6l7fqoea  于 2023-10-21  发布在  Python
关注(0)|答案(1)|浏览(130)

此问题已在此处有答案

How can I Install a Python module within code?(13个回答)
4天前关闭。
我想做一个文件下载脚本。
我可以在Python脚本中使用pip安装模块吗?
(还有其他问题,但它们已经过时了。
我的代码如下所示:

import pip

try:
    import requests
except ImportError:
    print('You do not have the REQUESTS module. Should the program install it for you? (y/n)')
    iyn = input()
    if iyn.lower() == 'y':
        print('Installing REQUESTS...')
        # How can I install a module???
    else:
        exit()

我试着用这个:
pip.main('pip install requests')
我以为它会安装requests模块,但它给了我这个错误:

Traceback (most recent call last):
  File "c:\Users\user\Documents\GitHub\program\program.py", line 16, in <module>
    pip.main('pip install requests')
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.240.0_x64__qbz5n2kfra8p0\Lib\site-packages\pip\__init__.py", line 13, in main
    return _wrapper(args)
           ^^^^^^^^^^^^^^
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.240.0_x64__qbz5n2kfra8p0\Lib\site-packages\pip\_internal\utils\entrypoints.py", line 43, in _wrapper
    return main(args)
           ^^^^^^^^^^
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.240.0_x64__qbz5n2kfra8p0\Lib\site-packages\pip\_internal\cli\main.py", line 64, in main
    cmd_name, cmd_args = parse_command(args)
                         ^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.240.0_x64__qbz5n2kfra8p0\Lib\site-packages\pip\_internal\cli\main_parser.py", line 79, in parse_command
    general_options, args_else = parser.parse_args(args)
                                 ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.240.0_x64__qbz5n2kfra8p0\Lib\optparse.py", line 1391, in parse_args
    args = largs + rargs
           ~~~~~~^~~~~~~
TypeError: can only concatenate list (not "str") to list

编辑:
我需要将命令分隔成一个列表,就像这样:
pip.main(['install', 'requests'])

b1zrtrql

b1zrtrql1#

您可以使用subprocess来运行pip命令,而不是pip模块本身。以下是如何修改代码以安装requests模块:

import subprocess

try:
    import requests
except ImportError:
    print("You haven't the REQUESTS module. Do you want to install? (y/n)")
    iyn = input()
    if iyn.lower() == 'y':
        print('Installing REQUESTS...')
        subprocess.check_call(['pip', 'install', 'requests'])
    else:
        exit()

相关问题