我试着运行这个脚本:
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
问题是:
如何将变量y
,m
,d
放入变量command
?
答案 0 :(得分:9)
Python有很多方法可以执行字符串格式化。最简单的方法之一是简单地将字符串的各个部分连接在一起:
#!/usr/bin/env python
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()
答案 1 :(得分:3)
command = 'ls /home/user/images/cappi/03000/%s/%s/%s' %(y,m,d)
答案 2 :(得分:2)
使用new format specifications,您可以按名称访问参数:
'ls /home/user/images/cappi/03000/{year}/{month}/{day}'.format(year=y, month=m, day=d)