سؤال

I have a doctest, and I want to save what a command I run into a variable, to use it in another function

   >>> sh("git finish", return_output=True).split("#")[1].split(":")[0]
   (here comes an int i want to save, say 900)

the sh is a command line function looking like this

# short alias for check_output
def sh(cmd, return_output=False):
    from subprocess import call
    open('/dev/shm/fail_output', 'w').close()
    with open('/dev/shm/fail_output', 'a+') as output:
        call(cmd, stderr=output, stdout=output, shell=True)
    with open('/dev/shm/fail_output', 'r') as output:
        if return_output:
            return output.read()
        print output.read()

return locals()
هل كانت مفيدة؟

المحلول

You can get the output of a command by using popen rather than call:

output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]

More information on the subprocess documentation page

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top