0

I am trying to write a script that opens a text file that contains specific lines which can be entered into the command window. Instead of having the user copy and paste these lines, I am trying to use subprocess to automatically make the commands run. Currently my code is this:

import sys 
from Tkinter import *
import tkFileDialog
import subprocess

master = Tk()
master.withdraw()

file_path = tkFileDialog.askopenfilename(title="Open command file")
print file_path
with open (file_path,"r") as infile:
    cmd1 = infile.readline()
    cmd2 = infile.readline()
    cmd3 = infile.readline()
    cmd4 = infile.readline()

p=subprocess.Popen("{}; {}; {}; {}".format(cmd1, cmd2, cmd3, cmd4), stdout=subprocess.PIPE)
for line in p.stdout:
    print line
p.wait()
print p.returncode
print 'complete'

The text file that the user selects has four commands which are all similar to the following:

program.exe commanduniquetoprogram "C:\\...." "C:\\...."

I don't know how the command line works, but if run in a command window, it does as it should without even opening the program. As it is now, when I run my program the only thing that seems to work is the first part program.exe as it opens up the program then throws a strange error. Instead, if the line is pasted into the command window, the program does not open up at all and does its job, which leads me to believe that subprocess doesn't like the spaces in the command line.

Any help is appreciated as I have no experience with the subprocess module!

Jeremy G
  • 2,189
  • 2
  • 13
  • 14
  • There are multiple errors in your code. Learn how to debug your code e.g., see [What are good ways to make my Python code run first time?](http://stackoverflow.com/q/299704/4279) Print the command that you pass to `subprocess.call()` -- you immediately will see unnecessary newlines in it. Read [`subprocess.call()` documentation](https://docs.python.org/3/library/subprocess.html#subprocess.call) that explicitly says that you should *not* use `stdout=PIPE` with it. Why don't you run the file directly as a batch file (add `.bat` extension) instead of reading the lines and trying to construct cm? – jfs Jul 10 '15 at 22:19
  • @J.F.Sebastian sorry I meant to write Popen instead of call – Jeremy G Jul 10 '15 at 22:26
  • It may also require a shell=True. See Doug Hellmann's PyMOTW http://pymotw.com/2/subprocess/index.html#module-subprocess Also, start with one command to the subprocess module and get it to work before adding more, and subprocess.check_output is easier to understand if you are just starting. –  Jul 11 '15 at 00:51

0 Answers0