I want to make a script which opens a command prompt window and input commands into that prompt without any user interaction. I have been using the subprocess module with little success. What I have so far:
def subprocess_cmd(command):
process = Popen(command,stdout=PIPE, shell=True)
proc_stdout = process.communicate()[0].strip()
print proc_stdout
subprocess_cmd('"C:\system\cmd.exe" & C:\dir\mybat.bat & C:\dir\gdal_translate C:\dir2\mypdf.pdf C:\dir\mytif.tif')
Now it runs through without error, but nothing happens. There should be a .tif file in the dir2 folder but as I said, nothing appears. When I run through the command prompt myself, it works fine.
asked Apr 16, 2015 at 1:11
Will B
3873 gold badges7 silver badges16 bronze badges
-
Instead of trying to run it in one line, why don't you create a batch file using python and then run that batch file through cmd.exe?Monacraft– Monacraft2015年04月16日 01:15:17 +00:00Commented Apr 16, 2015 at 1:15
-
I'm a bit rusty on Windows shell stuff, but does that first cmd.exe actually do what you intend? I think it will launch a new shell, and it would never get to the commands after the & until you manually exit the shell.Eric Renouf– Eric Renouf2015年04月16日 01:17:15 +00:00Commented Apr 16, 2015 at 1:17
1 Answer 1
I think the problem is you are not calling the methods and constants from the subprocess class. This worked for me in Python 3:
import subprocess
def subprocess_cmd(command,c="C:\\Users\\Alex"):
process = subprocess.Popen(command,stdout=subprocess.PIPE,shell=True,cwd=c)
proc_stdout = process.communicate()[0].strip()
print(proc_stdout)
>>> subprocess_cmd('"cmd.exe" && "C:\\Users\\Alex\\test.bat"','C:\\Users\\Alex\\')
b'Microsoft Windows [Version 6.3.9600]\r\n(c) 2013 Microsoft Corporation. All rights reserved.\r\n\r\nC:\\Users\\Alex>\r\nC:\\Users\\Alex>mkdir thisisanewdirectory'
>>> subprocess_cmd('test.bat')
b'C:\\Users\\Alex>mkdir thisisanewdirectory'
answered Apr 16, 2015 at 1:23
Alex W
38.5k13 gold badges115 silver badges115 bronze badges
Sign up to request clarification or add additional context in comments.
10 Comments
Will B
I just made it easier on myself by using: from subprocess import Popen. I tried it the way you have written and it still doesn't work.
Will B
The thing is the C:\dir\mybat.bat seems to be printing to the Python Interpreter, so it is recognizing it.
Alex W
@WillB Maybe the subprocess's working directory is currently set to where the Python executable is? Is this relevant? Also, you have only one command wrapped in quotes could that be part of the issue?
Alex W
The problem seems to be with
cmd. I think this comment explains what you're seeing. And you may have to run those commands separately.Will B
So you're saying I should run the (& [...] command1 & command2) line, but seperately. Could you explain a bit further if you have the time? Thanks for looking into it.
|
lang-py