首页 > 解决方案 > ModuleNotFoundError:没有名为“apache_beam”的模块,但它实际已安装

问题描述

操作系统:BigSur M1

蟒蛇版本:3.8.6 点数:21.1.2

我正在尝试运行从 gcp 数据流示例中获得的以下代码:

import argparse
import logging
import re

import apache_beam as beam
from apache_beam.io import ReadFromText
from apache_beam.io import WriteToText
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import SetupOptions


class WordExtractingDoFn(beam.DoFn):
"""Parse each line of input text into words."""
def process(self, element):
 """Returns an iterator over the words of this element.

 The element is a line of text.  If the line is blank, note that, too.

 Args:
   element: the element being processed

 Returns:
   The processed element.
 """
 return re.findall(r'[\w\']+', element, re.UNICODE)


def run(argv=None, save_main_session=True):
"""Main entry point; defines and runs the wordcount pipeline."""
parser = argparse.ArgumentParser()
parser.add_argument(
   '--input',
   dest='input',
   default='gs://dataflow-samples/shakespeare/kinglear.txt',
   help='Input file to process.')
parser.add_argument(
   '--output',
   dest='output',
   required=True,
   help='Output file to write results to.')
known_args, pipeline_args = parser.parse_known_args(argv)

# We use the save_main_session option because one or more DoFn's in this
# workflow rely on global context (e.g., a module imported at module level).
pipeline_options = PipelineOptions(pipeline_args)
pipeline_options.view_as(SetupOptions).save_main_session = save_main_session

# The pipeline will be run on exiting the with block.
with beam.Pipeline(options=pipeline_options) as p:

 # Read the text file[pattern] into a PCollection.
 lines = p | 'Read' >> ReadFromText(known_args.input)

 counts = (
     lines
     | 'Split' >> (beam.ParDo(WordExtractingDoFn()).with_output_types(str))
     | 'PairWIthOne' >> beam.Map(lambda x: (x, 1))
     | 'GroupAndSum' >> beam.CombinePerKey(sum))

 # Format the counts into a PCollection of strings.
 def format_result(word, count):
   return '%s: %d' % (word, count)

 output = counts | 'Format' >> beam.MapTuple(format_result)

 # Write the output using a "Write" transform that has side effects.
 # pylint: disable=expression-not-assigned
 output | 'Write' >> WriteToText(known_args.output)


if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
run()

但是当我尝试时,我不断收到此错误,但我无法找出问题所在:

 python hello.py --output
Traceback (most recent call last):
  File "hello.py", line 26, in <module>
    import apache_beam as beam
ModuleNotFoundError: No module named 'apache_beam'

这是 pip 的输出:

 pip list
Package                         Version
------------------------------- ---------
apache-beam                     2.29.0

我按照 gcp 的教程使用了虚拟环境和所有内容。生成了密钥和所有内容,但我已经坚持了几个小时。任何帮助是极大的赞赏。

谢谢

标签: pythongoogle-cloud-platformgoogle-cloud-dataflowapache-beam

解决方案


推荐阅读