简体   繁体   中英

Running batch command in Python script

I am trying to execute a batch command in a Python script, simply showing the PDFs file name. Basically, the Python script is in a folder C:\\users\\me\\desktop\\python which should execute a command on a different folder on the desktop ( C:\\users\\me\\desktop\\some-folder ), which has subfolders with PDFs in it.

Here is the code:

from subprocess import call
import os

for root, dirs, files in os.walk("../some-folder"):
    for pdf_file in files:
        if pdf_file.endswith(".pdf"):
            pdf_file_path = os.path.join(root, pdf_file)
            os.chdir(root)
            call('for %%f in (*.pdf) do @echo %%f')

The result I get is "file not found".

First, since you're activating built-in DOS commands, you'd have to set shell=True to run such commands.

Second, even with that it won't work, since double percent are reserved for scripts. In-line command require one sole % .

And third: don't use os.chdir , it's bad practice. Better use cwd option of subprocess calls, allows to locally change the directory when running the command.

That would work:

call('for %f in (*.pdf) do @echo %f',shell=True,cwd=root)

Of course this is probably an example since your command accomplishes nothing: you don't get the output back in your python script, you don't check return code...

If you want to get the list of *.pdf in python in root directory (with full path), I guess that you know

list_of_pdfs = glob.glob(os.path.join(root,"*.pdf"))

or in relative:

list_of_pdfs = [x for x os.listdir(root) if fnmatch.fnmatch(x,"*.pdf")]

but since you're in an os.walk loop, you'll get the output as many times as there are .pdf files, so it's not very performant / bad design & complexity.

For your whole conversion loop I would call the converter for each file, no need for .bat scripting, you have python!:

from subprocess import call
import os

for root, dirs, files in os.walk("../some-folder"):
    for pdf_file in files:
        if pdf_file.endswith(".pdf"):
           call([r"C:\xpdf\bin32\pdftotext","-raw",pdf_file], cwd=root)

passing arguments in a list automatically handles spaces in filenames.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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