在Python中将数据附加到现有文件(本地)似乎很容易,尽管远程操作并不那么容易(至少我发现)。有没有一些直接的方法可以实现这一点?
我尝试使用:
import subprocess
cmd = ['ssh', 'user@example.com',
'cat - > /path/to/file/append.txt']
p = subprocess.Popen(cmd, stdin=subprocess.PIPE)
inmem_data = 'foobar\n'
for chunk_ix in range(0, len(inmem_data), 1024):
chunk = inmem_data[chunk_ix:chunk_ix + 1024]
p.stdin.write(chunk)
但也许这不是正确的方法;所以我尝试发布查询:
import urllib
import urllib2
query_args = { 'q':'query string', 'foo':'bar' }
request = urllib2.Request('http://example.com:8080/')
print 'Request method before data:', request.get_method()
request.add_data(urllib.urlencode(query_args))
print 'Request method after data :', request.get_method()
request.add_header('User-agent', 'PyMOTW (http://example.com/)')
print
print 'OUTGOING DATA:'
print request.get_data()
print
print 'SERVER RESPONSE:'
print urllib2.urlopen(request).read()
但是我得到连接被拒绝
,所以我显然需要某种类型的表单处理程序,不幸的是我对此一无所知。有推荐的方法来实现这一点吗?谢谢。
最佳答案
如果我理解正确,您正在尝试将远程文件附加到本地文件...
我建议使用织物... http://www.fabfile.org/
我已经尝试过使用文本文件进行此操作,效果很好。
记住在运行脚本之前安装fabric:
pip install fabric
将远程文件附加到本地文件(我认为这是不言自明的):
from fabric.api import (cd, env)
from fabric.operations import get
env.host_string = "127.0.0.1:2222"
env.user = "jfroco"
env.password = "********"
remote_path = "/home/jfroco/development/fabric1"
remote_file = "test.txt"
local_file = "local.txt"
lf = open(local_file, "a")
with cd(remote_path):
get(remote_file, lf)
lf.close()
将其作为任何Python文件运行(不必使用“fab”应用程序)
希望这有帮助
编辑:在远程文件末尾写入变量的新脚本:
再说一遍,使用 Fabric 非常简单
from fabric.api import (cd, env, run)
from time import time
env.host_string = "127.0.0.1:2222"
env.user = "jfroco"
env.password = "*********"
remote_path = "/home/jfroco/development/fabric1"
remote_file = "test.txt"
variable = "My time is %s" % time()
with cd(remote_path):
run("echo '%s' >> %s" % (variable, remote_file))
在示例中,我使用 time.time() 但可以是任何东西。
关于Python远程追加文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27893929/