Reputation: 67
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)
Upvotes: 1
Views: 277
Reputation: 121
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)
Upvotes: 4
Reputation: 14458
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"
Upvotes: 1