简体   繁体   English

如何通过命令行执行导入第三方模块的 python 脚本

[英]How to execute python scripts that import third party modules via the command line

I have a py file that preforms a google search using the system arguments passed to it and opens the first five results of the search as separate browser tabs (this is an exercise from the book Automate the Boring Stuff ).我有一个 py 文件,它使用传递给它的系统 arguments 执行 google 搜索,并将搜索的前五个结果作为单独的浏览器选项卡打开(这是Automate the Boring Stuff一书中的一个练习)。

I would like to execute this script via the Windows run command and have therefore created a BAT file.我想通过 Windows 运行命令执行此脚本,因此创建了一个 BAT 文件。

Currently, when I execute the BAT file, a "module not found" error is returned.目前,当我执行 BAT 文件时,会返回“找不到模块”错误。

I suspected this issue was related to the fact that the modules required by the py file were only installed in the virtual environment of my specific python project (I have a project specifically for the exercises in this book).我怀疑这个问题与py文件所需的模块仅安装在我的特定python项目的虚拟环境中有关(我有一个专门用于本书练习的项目)。 Therefore, I installed the necessary modules directly into the environment of my main Python installation.因此,我将必要的模块直接安装到我的主要 Python 安装的环境中。 Unfortunately, this had no effect.不幸的是,这没有效果。

I then revised my BAT file by adding a line to activate my virtual environment before the line to execute my py file.然后,我通过在执行 py 文件的行之前添加一行来激活我的虚拟环境来修改我的 BAT 文件。 This seemed to prevent my py file from being executing by the BAT file.这似乎阻止了我的 py 文件被 BAT 文件执行。

I'm somewhat familiar with Python but new to BAT files and the command line in general.我对 Python 有点熟悉,但对 BAT 文件和命令行一般来说是新手。 I've read through a basic command line tutorial but couldn't find anything that helps.我已经阅读了一个基本的命令行教程,但找不到任何有用的东西。

I'm not sure how to resolve this issue and if possible would like to avoid polluting my main python environment with tons of modules.我不确定如何解决这个问题,如果可能的话,我想避免用大量模块污染我的主要 python 环境。 Is this possible and, if so, what am I missing?这是可能的,如果是的话,我错过了什么?

.bat file .bat 文件

@py.exe C:\Users\Betty\PycharmProjects\Automate_the_Boring_Stuff\12\searchpypi.py %*
@pause

.py file .py 文件

#! python3
# searchpypi.py  - Opens several search results.


import sys
import webbrowser

import requests

import bs4

print('Searching...')    # display text while downloading the search result page
res = requests.get('https://google.com/search?q=' 'https://pypi.org/search/?q='
                   + ' '.join(sys.argv[1:]))
res.raise_for_status()

# Retrieve top search result links.
soup = bs4.BeautifulSoup(res.text, 'html.parser')
# Open a browser tab for each result.
linkElems = soup.select('.package-snippet')
numOpen = min(5, len(linkElems))

# Open a browser tab for each result.
for i in range(numOpen):
    urlToOpen = 'https://pypi.org' + linkElems[i].get('href')
    print('Opening', urlToOpen)
    webbrowser.open(urlToOpen)

edit (Fri Mar 05 16:41:27 2021 UTC):编辑(UTC 2021 年 3 月 5 日星期五 16:41:27):

Error message (copied from command line):错误消息(从命令行复制):

Traceback (most recent call last):
  File "C:\Users\Betty\PycharmProjects\Automate_the_Boring_Stuff\12\searchpypi.py", line 8, in <module>
    import requests
ModuleNotFoundError: No module named 'requests'
Press any key to continue . . .

edit (Sat Mar 06 07:39:43 2021 UTC):编辑(UTC 2021 年 3 月 6 日星期六 07:39:43):

Pip Details: Pip 详细信息:

C:\Users\Betty>pip -V
pip 21.0.1 from c:\python38\lib\site-packages\pip (python 3.8)

C:\Users\Betty>pip3 list
Package          Version
---------------- ----------
appdirs          1.4.4
certifi          2020.12.5
chardet          4.0.0
distlib          0.3.1
filelock         3.0.12
idna             2.10
pip              21.0.1
pipenv           2020.11.15
requests         2.25.1
setuptools       41.2.0
six              1.15.0
urllib3          1.26.3
virtualenv       20.2.2
virtualenv-clone 0.5.4
wheel            0.34.2

C:\Users\Betty>

Automating everything would means:自动化一切意味着:

  • creating a virtual environment for this Python script为此 Python 脚本创建虚拟环境
  • sourcing it采购它
  • installing dependencies安装依赖项
  • run the scrip运行脚本
  • optional (cleanup if necessary)可选(必要时清理)

There is a way to do it on Bash, but I am not sure if the same applies for the Windows shell.有一种方法可以在 Bash 上执行此操作,但我不确定 Windows shell 是否同样适用。

First you need to put all dependencies in a requirements.txt file.首先,您需要将所有依赖项放在 requirements.txt 文件中。 Each dependency should take one line in the document.每个依赖项都应该在文档中占一行。

requirements.txt 's content: requirements.txt的内容:

webbrowser
beautifulsoup4

And the automation script.sh :和自动化script.sh

# creates a venv folder that contains a copy of python3 packages to isolate any further changes in packages from the system installation
python3 -m venv venv  
 # tell the shell to use the created virtual environment
source venv/bin/activate
# install requirements
pip3 install -r requirements.txt 
# run the script
python3 your_script_filename.py
# remove the venv
rm -rf venv
# deactivate the virtual environment
deactivate

That's a very basic script that resembles manual invocation of the Python script.这是一个非常基本的脚本,类似于手动调用 Python 脚本。 There is so much space for improvements.有很大的改进空间。 The venv could be placed in the OS temporary folder and can be left there for reuse next time. venv 可以放在操作系统临时文件夹中,可以留在那里以备下次使用。 That will remove the need for recreating the venv and installing the requirements.这将消除重新创建 venv 和安装要求的需要。

I know this is not exactly what you want but I hope it got you a little bit further我知道这不是你想要的,但我希望它能让你更进一步

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM