简体   繁体   中英

printing output python subprocess

Two days into python and I'm trying to do some simple things but struggling.

When I run the script below using ls as the example command input, ssh prompts me for password, then it spits out this:

<__main__.sshcommand object at 0x7fd0d1136b50>

If I hard set command inside of the sshcommand class (for instance replacing command with 'ls'), and print it, it works great.

Thanks for all advice in advance.

import subprocess

class sshcommand(object):
    def __init__(self, command):
        subprocess.check_output(['ssh', 'localhost', command]).splitlines()

command = raw_input("command> ")

print sshcommand(command)

The problem is that your code doesn't store or return the result in any way.

Does this really need to be a class? If not, it's much simpler as a function:

import subprocess

def sshcommand(command):
    return subprocess.check_output(['ssh', 'localhost', command]).splitlines()

command = raw_input("command> ")
print sshcommand(command)

If it absolutely must be a class:

import subprocess

class sshcommand(object):
    def __init__(self, command):
        self.result = subprocess.check_output(['ssh', 'localhost', command]).splitlines()

    def __str__(self):
        return self.result

command = raw_input("command> ")
print sshcommand(command)

Define a __str__ method on your class. For example, you could write

import subprocess

class sshcommand(object)
    def __init__(self, command):
        self.command = command
        subprocess.check_output(['ssh', 'localhost', command]).splitlines()

    def __str__(self):
        return 'ssh localhost "%s"' % command

command = raw_input("command> ")

print '%s' % sshcommand('foo bar')

which prints

ssh localhost "foo bar"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM