如何从python脚本中执行python脚本

时间:2018-12-21 00:59:43

标签: python shell command-line

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

这是pdfminer文档的链接:

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

自述文件显示了如何从终端os提示符下调用该文件,如下所示:

pdf2txt.py samples/simple1.pdf

在这里,pdf2txt.py通过pip命令安装在全局空间中:

pip安装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

我该怎么做?

2 个答案:

答案 0 :(得分: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的任何意义。

答案 1 :(得分:0)

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

  1. 使用操作系统

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

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