简体   繁体   中英

Bash script can be called from command line, but not from Python script

I have the following script utils/pdf2image.sh :

#!/bin/bash
pdftoppm -png $1 $2

and the following snippet of Python code:

script_path = os.path.join(os.getcwd(), 'utils', 'pdf2image.sh') + ' ' + invoice_path + ' ' + invoice_path[:-4]
subprocess.call(script_path, shell=True)

When I call the script in command line, it works, but when I call it from Python, it doesn't, saying that pdftoppm doesn't work. I checked and poppler-utils is installed. I suspect that pdftoppm can't be seen from Python environment. Any idea why?

The user's PATH and the script's PATH aren't necessarily the same, so it seems that the BASH script being called from inside the Python script doesn't know where pdftoppm is.

You have two options:

  1. Calling the full path to pdftoppm inside the BASH script:
#!/bin/bash
/usr/bin/pdftoppm -png $1 $2
  1. Calling pdftoppm directly from the Python script:
script_path = os.path.join(os.getcwd(), 'utils', 'pdf2image.sh') + ' ' + invoice_path + ' ' + invoice_path[:-4]
subprocess.Popen(['/usr/bin/pdftoppm', '-png', invoice_path, invoice_path[:-4]])

From what I'm understanding on your problem, the Python code is unable to locate the pdftoppm . This can happen if that binary is not present in the $PATH .

I would recommend to make use of the absolute path to the pdftoppm if that's the case in that shell script and then try invoking the shell script from Python.

Though as the comments to your question have pointed out already that the script's piece of work can be done by subprocess itself, you should give that a shot as well:)

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