Trying to access the correct directory

206 views Asked by At

So I'm trying to write a script that'll use the command line in Windows, and it's defaulting to a structure that is under my Python directory - I don't want that.

import subprocess
import time
subprocess.call(r"""Cscript %windir%/System32/Printing_Admin_Scripts/en-US/Prnport.vbs -a -r "saturn.print.mediag.com" -h "saturn.print.mediag.com" -o raw""")
time.sleep(5)
subprocess.call(r"""rundll32 printui.dll, PrintUIEntry /if /b "Saturn" /f w:\printers\toshibae3511\eng\est_c2.inf /r "saturn.print.mediag.com" /m "TOSHIBA e-STUDIO Color PS3""")
raw_input("press any key to exit")

The first subprocess call should execute the script prnport.vbs in c:\windows\system32, etc, etc, however instead it goes to like c:\python27\projects\printer setup\%windir%\system32, etc etc

How do I make it go to the correct directory, which might (though probably won't) vary per computer?

2

There are 2 answers

0
jadkik94 On

You need to use environment variables to get windir, %WINDIR% won't expand to the value you expect it to, so it is assumed relative to current working directory. You can use os.environ["WINDIR"] or os.getenv("WINDIR", "default_value"), according to: this link

I'm not sure if that's it, I'm not on Windows, but you need something similar:

import os
windir = os.environ["WINDIR"]
subprocess.call(r'Cscript %s/System32/Printing_Admin_Scripts/en-US/Prnport.vbs -a -r "saturn.print.mediag.com" -h "saturn.print.mediag.com" -o raw' % (windir,))

And use triple quotes """ for multiple lines. You don't need them for a single line use ' or "

Otherwise, you would change the current working directory with:

import os
os.chdir('C:\\Windows\\Sytem32\\')
subprocess.call(r'Cscript ./System32/Printing_Admin_Scripts/en-US/Prnport.vbs -a -r "saturn.print.mediag.com" -h "saturn.print.mediag.com" -o raw')
1
bereal On

You need to use os.path.expandvars on the path to replace "%windir%".

Also, aside from the question, it's better to pass a list of arguments, not a single long string to subprocess.call, i.e.

subprocess.call(['rundll32', 'printui.dll'...])