Python远程追加文件

标签 python post urllib2 urllib

在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/

相关文章:

python - 索引 JSON 搜索 python

python - PyInstaller: AttributeError 'module' 对象没有属性 'register'

c# - 使用 WebClient 将数组作为消息正文的一部分传递以进行发布操作

javascript - 使用node.js和express处理POST请求

PHP检查是否有选择上传的文件

python - urllib.request SSL 连接 Python 3

python - arg 规则,kwarg 拆包

python - 我如何将垂直线添加到他们选择的 seaborn dist 地 block ? [单个地 block 中的多个分布]

python - 几次调用后,通过代理的 urllib2.urlopen 失败

python - 用urllib2指定请求方法?