简体   繁体   中英

Calling subprocess.call() on a .exe in another directory

I have some .dot files I want to convert to pdf with python. The command goes like this:

dot -Tpdf -o output.pdf input.dot

This command works if I execute it straight from cmd. But using Pythons subprocess.call it does not work.

The dot.exe is in a separate directory with dependency on other files, I've tried running it like this:

subprocess.call(['C:/graphviz-2.38/release/bin/', 'dot', '-Tpdf', '-o ' + file + '.pdf' + file])

And like this ('dot' added to path)

subprocess.call(['C:/graphviz-2.38/release/bin/dot', '-Tpdf', '-o' + file + '.pdf' + file])

The latter just runs dot.exe and doesn't take any arguments, the former gives me the following error:

    Traceback (most recent call last):
  File "xmltodot2.py", line 22, in <module>
    subprocess.call(['C:/graphviz-2.38/release/bin/', 'dot', '-Tpdf', '-o ' + file + '.pdf' + file])
  File "C:\Python27\lib\subprocess.py", line 172, in call
    return Popen(*popenargs, **kwargs).wait()
  File "C:\Python27\lib\subprocess.py", line 394, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 644, in _execute_child
    startupinfo)
WindowsError: [Error 5] Access is denied

How can I run dot.exe that has dependencies on files in its directory from another directory?

I'm new to Python and unsure of the syntax.

Thanks!

EDIT:

Full code

import os, fnmatch, subprocess, string
from subprocess import call

# opens the directory
listOfFiles = os.listdir('.')
# file extensions to look for
pattern = "*.xml"
pattern2 = "*.dot"
path = "C:/graphviz-2.38/release/bin"

#Converts every dot-file in the directory to pdf
for file in listOfFiles:
if fnmatch.fnmatch(file, pattern2):
    os.chdir(path)
    subprocess.call(['C:/graphviz-2.38/release/bin/dot', '-Tpdf', '-o' +         
file + '.pdf', file])
    print("Converted " + file + " to pdf")
  1. You can try to change the working directory from within your script to control execution context. This is like cd in your command line reproduction. os.chdir is a standard library method to change cwd.

  2. Ensure your script is running with sufficient permissions.

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