2

When I run a command through subprocess I get exit status 1 without my print or the error raised.

here is my code:

    def generate_model(self):
        if not ((self.username == None) or (self.password == None) or (self.database == None)):
            cmd = "python -m pwiz -e %s -H %s -u %s -P %s %s > %s"%(self.engine,self.host,self.username,self.password,self.database,self.database+".py")
            print subprocess.check_call(cmd)
        else:
            raise ValueError

command asks an input once terminal is opened. After that it closes with exit status 1

When I run the same command directly in command prompt it works fine

glls
  • 2,325
  • 1
  • 22
  • 39
Harwee
  • 1,601
  • 2
  • 21
  • 35
  • 1
    Did you try putting your command inside an array with each string separate ? i.e `['python', '-m', 'pwiz']`... You can use `shlex.split` also. – Idos May 27 '16 at 07:13
  • Yes I have tried it, even that returns `exit code 1` – Harwee May 27 '16 at 07:16
  • The advise @Idos gave is a really good one, since it is required to prevent command injection. Never construct commands as strings. To solve the problem you should print `cmd` and run the program. Using `>` redirection might need `shell=True` to be set for `check_call()`. – Klaus D. May 27 '16 at 07:52

1 Answers1

3

subprocess.check_call() does not run the shell by default and therefore the redirection operator > won't work. To redirect stdout, pass stdout parameter instead:

with open(filename, 'wb', 0) as file:
    check_call([sys.executable, '-m', 'pwiz', '-e', ...], stdout=file)

Related: Python subprocess.check_output(args) fails, while args executed via Windows command line work OK.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670