1

I am using Python 3.4.3. What am I trying to do is, storing a cmd command's output into a variable without printing that into command line. Here I found the answer but it works on the old version but on 3.4.3, variable "var" contains some random characters. And for example if I try to test that with the command "dir", it prints a mess.

import subprocess
from subprocess import Popen, PIPE
var = subprocess.Popen(COMMAND, stdin = PIPE, stdout = PIPE, stderr = PIPE).communicate()[1]
print(var)
Community
  • 1
  • 1
ozcanovunc
  • 703
  • 1
  • 8
  • 29

2 Answers2

0

If I understood well you just want to run an external command and get the output into a variable.

import subprocess

def foo():
    return subprocess.Popen(COMMAND.split(), stdout=subprocess.PIPE).communicate()[0]

From the subprocess documentation :

Replacing /bin/sh shell backquote
---------------------------------
output=`mycmd myarg`
==>
output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]

Note that the COMMAND.split() is a bit... tricky. For example :

var1 = subprocess.Popen(['echo', '"Hey', 'StackOverflow!"'], stdout=subprocess.PIPE).communicate()[0]
# String contained in var1: "Hey StackOverflow!"\n
var2 = subprocess.Popen(['echo', 'Hey StackOverflow!'], stdout=subprocess.PIPE).communicate()[0]
# String contained in var2: Hey StackOverflow!\n
var1 != var2
# True
FunkySayu
  • 7,641
  • 10
  • 38
  • 61
0

subprocess.check_output does what you want: https://docs.python.org/2/library/subprocess.html#subprocess.check_output

thanasis2028
  • 125
  • 5