【问题标题】:how to execute a python script from within a python script [duplicate]如何从python脚本中执行python脚本[重复]
【发布时间】:2018-12-21 00:59:42
【问题描述】:

我需要从我的 python 代码中调用 pdfminer 顶级 python 脚本:

这里是 pdfminer 文档的链接:

https://github.com/pdfminer/pdfminer.six

自述文件显示了如何从终端操作系统提示符调用它,如下所示:

pdf2txt.py samples/simple1.pdf

这里,pdf2txt.py是通过pip命令安装到全局空间的:

pip install pdfminer.six

我想从我的python代码中调用它,它位于项目根目录中:

my_main.py(在项目根目录下)

for pdf_file_name in input_file_list:
   # somehow call pdf2txt.py with pdf_file_name as argument
   # and write out the text file in the output_txt directory

我该怎么做?

【问题讨论】:

  • 可以像模块一样导入脚本吗?在脚本中添加一个 main,如果它还没有的话。那么当你导入文件时,你可以调用 main.

标签: python shell command-line


【解决方案1】:

我认为您需要在代码中导入它并按照docs 中的示例进行操作:

from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfpage import PDFTextExtractionNotAllowed
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice
# Open a PDF file.
fp = open('mypdf.pdf', 'rb')
# Create a PDF parser object associated with the file object.
parser = PDFParser(fp)
# Create a PDF document object that stores the document structure.
# Supply the password for initialization.
document = PDFDocument(parser, password)
# Check if the document allows text extraction. If not, abort.
if not document.is_extractable:
raise PDFTextExtractionNotAllowed
# Create a PDF resource manager object that stores shared resources.
rsrcmgr = PDFResourceManager()
# Create a PDF device object.
device = PDFDevice(rsrcmgr)
# Create a PDF interpreter object.
interpreter = PDFPageInterpreter(rsrcmgr, device)
# Process each page contained in the document.
for page in PDFPage.create_pages(document):
interpreter.process_page(page)

鉴于您正在做一些平常的事情,我认为使用 shell 没有任何意义。

【讨论】:

    【解决方案2】:

    我会建议两种方法来做到这一点!

    1. 使用操作系统

      import os
      os.system("pdf2txt.py samples/simple1.pdf")
      
    2. 使用子进程

      import subprocess
      subprocess.call("pdf2txt.py samples/simple1.pdf", shell=True)
      

    【讨论】:

    • 谢谢。这行得通。其中哪一个更好?使用 os.system 或 subprocess.call?为什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 2019-02-07
    • 2015-10-23
    • 2017-09-03
    相关资源
    最近更新 更多