1

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)

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.