10

I'm try to run this script:

hostname = '192.168.3.4'
port = 22
username = 'username'
password = 'mypassword'
y = "2012"
m = "02"
d = "27"

if __name__ == "__main__":
   s = paramiko.SSHClient()
   s.load_system_host_keys()
   s.connect(hostname, port, username, password)
   command = 'ls /home/user/images/cappi/03000/y/m/d'
   s.close

The question is: how can I put the variables y,m,d into the variable command ?

4 Answers 4

24

Python has lots of ways to perform string formatting. One of the simplest is to simply concatenate the parts of your string together:

#!/usr/bin/env python
import paramiko

hostname = "192.168.3.4"
port = 22
username = "username"
password = "mypassword"
y = "2012"
m = "02"
d = "27"

def do_it():
    s = paramiko.SSHClient()
    s.load_system_host_keys()
    s.connect(hostname, port, username, password)
    command = "ls /home/user/images/cappi/03000/" + y + "/" + m + "/" + d
    stdin, stdout, stderr = s.exec_command(command)
    for line in stdout.readlines():
        print line
    s.close()

if __name__ == "__main__":
    do_it()
Sign up to request clarification or add additional context in comments.

6 Comments

I don't see that that's significantly better. Now if you had said '/'.join([y, m, d]) you'd have a case.
The problem here is not syntax, the problem is that if you run a1 + a2 + a3 + ... + an, you're creating and destroying n-1 temporary strings. join in Python only creates 1 string. This is a bad habit to get into.
I would point out 1. n is very small here, 2. the + operator is very readable here, and 3. greaterdebater.com/blog/gabe/post/7
@matt: I think we're going to have to agree to disagree here. This is a convention, and getting in the habit of doing it properly is best, IMO.
Using the plus sign for string concatenation is the most un-Pythonic way to do it. Python has like 4 ways to format stings. Percent encoding, f strings, .format, and templates are all preferred over the plus sign. ALSO escape terminal input. pipes.quote is there for a reason.
|
4

Using the new format specifications, you can access arguments by name:

'ls /home/user/images/cappi/03000/{year}/{month}/{day}'.format(year=y, month=m, day=d)

3 Comments

You need to put an f in front of the string.
@kagronick since Python 3.6 you can use f-strings (PEP 498), but the above .format(...) string is perfectly valid since Python 2.6 and in Python 3.x.
Oh I didn't scroll to the right on my phone. .format was new in 2006 so I assumed f strings were what you were talking about.
4

I prefer

command = f"ls /home/user/images/cappi/03000/{y}/{m}/{d}"

Comments

3
command = 'ls /home/user/images/cappi/03000/%s/%s/%s' %(y,m,d)

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.