标签归档:ssh

Emacs适用于Python的批量缩进

问题:Emacs适用于Python的批量缩进

如果我想在代码块中添加try / except,则在Emacs中使用Python,我经常发现我必须逐行缩进整个代码块。在Emacs中,如何立即缩进整个块。

我不是经验丰富的Emacs用户,但是发现它是通过ssh工作的最佳工具。我在命令行(Ubuntu)上使用Emacs,而不是作为gui,如果有什么不同的话。

Working with Python in Emacs if I want to add a try/except to a block of code, I often find that I am having to indent the whole block, line by line. In Emacs, how do you indent the whole block at once.

I am not an experienced Emacs user, but just find it is the best tool for working through ssh. I am using Emacs on the command line(Ubuntu), not as a gui, if that makes any difference.


回答 0

如果您正在使用Emacs编程Python,那么您可能应该使用python-mode。使用python-mode,在标记代码块之后,

C-c >C-c C-l 将区域右移4个空格

C-c <C-c C-r 将区域向左移动4个空格

如果您需要将代码缩进两个级别,或者需要一定程度的缩编,则可以在命令前加上一个参数:

C-u 8 C-c > 将区域右移8个空格

C-u 8 C-c < 将区域向左移动8个空格

另一种选择是使用M-x indent-rigidly绑定到C-x TAB

C-u 8 C-x TAB 将区域右移8个空格

C-u -8 C-x TAB 将区域向左移动8个空格

用于文本矩形而不是文本行的矩形命令也很有用。

例如,在标记矩形区域后,

C-x r o 插入空格以填充矩形区域(有效地向右移动代码)

C-x r k 杀死矩形区域(有效地将代码向左移动)

C-x r t提示输入一个字符串来替换矩形。输入C-u 8 <space>后将输入8个空格。

PS。使用Ubuntu,要将python-mode设置为所有.py文件的默认模式,只需安装该python-mode软件包。

If you are programming Python using Emacs, then you should probably be using python-mode. With python-mode, after marking the block of code,

C-c > or C-c C-l shifts the region 4 spaces to the right

C-c < or C-c C-r shifts the region 4 spaces to the left

If you need to shift code by two levels of indention, or some arbitary amount you can prefix the command with an argument:

C-u 8 C-c > shifts the region 8 spaces to the right

C-u 8 C-c < shifts the region 8 spaces to the left

Another alternative is to use M-x indent-rigidly which is bound to C-x TAB:

C-u 8 C-x TAB shifts the region 8 spaces to the right

C-u -8 C-x TAB shifts the region 8 spaces to the left

Also useful are the rectangle commands that operate on rectangles of text instead of lines of text.

For example, after marking a rectangular region,

C-x r o inserts blank space to fill the rectangular region (effectively shifting code to the right)

C-x r k kills the rectangular region (effectively shifting code to the left)

C-x r t prompts for a string to replace the rectangle with. Entering C-u 8 <space> will then enter 8 spaces.

PS. With Ubuntu, to make python-mode the default mode for all .py files, simply install the python-mode package.


回答 1

除了默认情况下indent-region映射到C-M-\的,矩形编辑命令对Python很有用。将区域标记为正常,然后:

  • C-x r tstring-rectangle):将提示您输入要插入每行的字符;非常适合插入一定数量的空格
  • C-x r kkill-rectangle):删除矩形区域;非常适合去除压痕

您也可以C-x r yyank-rectangle),但这很少有用。

In addition to indent-region, which is mapped to C-M-\ by default, the rectangle edit commands are very useful for Python. Mark a region as normal, then:

  • C-x r t (string-rectangle): will prompt you for characters you’d like to insert into each line; great for inserting a certain number of spaces
  • C-x r k (kill-rectangle): remove a rectangle region; great for removing indentation

You can also C-x r y (yank-rectangle), but that’s only rarely useful.


回答 2

indent-region映射C-M-\应该可以解决问题。

indent-region mapped to C-M-\ should do the trick.


回答 3

我一直在使用此功能来处理缩进和缩进:

(defun unindent-dwim (&optional count-arg)
  "Keeps relative spacing in the region.  Unindents to the next multiple of the current tab-width"
  (interactive)
  (let ((deactivate-mark nil)
        (beg (or (and mark-active (region-beginning)) (line-beginning-position)))
        (end (or (and mark-active (region-end)) (line-end-position)))
        (min-indentation)
        (count (or count-arg 1)))
    (save-excursion
      (goto-char beg)
      (while (< (point) end)
        (add-to-list 'min-indentation (current-indentation))
        (forward-line)))
    (if (< 0 count)
        (if (not (< 0 (apply 'min min-indentation)))
            (error "Can't indent any more.  Try `indent-rigidly` with a negative arg.")))
    (if (> 0 count)
        (indent-rigidly beg end (* (- 0 tab-width) count))
      (let (
            (indent-amount
             (apply 'min (mapcar (lambda (x) (- 0 (mod x tab-width))) min-indentation))))
        (indent-rigidly beg end (or
                                 (and (< indent-amount 0) indent-amount)
                                 (* (or count 1) (- 0 tab-width))))))))

然后将其分配给键盘快捷键:

(global-set-key (kbd "s-[") 'unindent-dwim)
(global-set-key (kbd "s-]") (lambda () (interactive) (unindent-dwim -1)))

I’ve been using this function to handle my indenting and unindenting:

(defun unindent-dwim (&optional count-arg)
  "Keeps relative spacing in the region.  Unindents to the next multiple of the current tab-width"
  (interactive)
  (let ((deactivate-mark nil)
        (beg (or (and mark-active (region-beginning)) (line-beginning-position)))
        (end (or (and mark-active (region-end)) (line-end-position)))
        (min-indentation)
        (count (or count-arg 1)))
    (save-excursion
      (goto-char beg)
      (while (< (point) end)
        (add-to-list 'min-indentation (current-indentation))
        (forward-line)))
    (if (< 0 count)
        (if (not (< 0 (apply 'min min-indentation)))
            (error "Can't indent any more.  Try `indent-rigidly` with a negative arg.")))
    (if (> 0 count)
        (indent-rigidly beg end (* (- 0 tab-width) count))
      (let (
            (indent-amount
             (apply 'min (mapcar (lambda (x) (- 0 (mod x tab-width))) min-indentation))))
        (indent-rigidly beg end (or
                                 (and (< indent-amount 0) indent-amount)
                                 (* (or count 1) (- 0 tab-width))))))))

And then I assign it to a keyboard shortcut:

(global-set-key (kbd "s-[") 'unindent-dwim)
(global-set-key (kbd "s-]") (lambda () (interactive) (unindent-dwim -1)))

回答 4

我是Emacs的新手,因此此答案可能对您毫无用处。

到目前为止,所提到的答案都没有覆盖字面量如dict或的重新缩进list。例如,如果您剪切并粘贴了以下文字并需要对其进行合理的缩进,则M-x indent-regionor或M-x python-indent-shift-rightcompany不会提供帮助:

    foo = {
  'bar' : [
     1,
    2,
        3 ],
      'baz' : {
     'asdf' : {
        'banana' : 1,
        'apple' : 2 } } }

感觉M-x indent-region应该在中做一些明智的事情python-mode,但是还不是这样。

对于将文字放在方括号中的特定情况,在相关行上使用TAB即可获得所需的内容(因为空格不起作用)。

因此,在这种情况下,我一直在快速记录键盘宏,例如<f3> C-n TAB <f4>F3,Ctrl-n(或向下箭头),TAB,F4,然后重复使用F4来应用宏可以节省几次击键。或者,您可以将C-u 10 C-x e其应用10次。

(我知道这听起来不多,但是尝试重新缩进100行垃圾文字而不丢失向下箭头,然后不得不上升5行并重复一遍;)。

I’m an Emacs newb, so this answer it probably bordering on useless.

None of the answers mentioned so far cover re-indentation of literals like dict or list. E.g. M-x indent-region or M-x python-indent-shift-right and company aren’t going to help if you’ve cut-and-pasted the following literal and need it to be re-indented sensibly:

    foo = {
  'bar' : [
     1,
    2,
        3 ],
      'baz' : {
     'asdf' : {
        'banana' : 1,
        'apple' : 2 } } }

It feels like M-x indent-region should do something sensibly in python-mode, but that’s not (yet) the case.

For the specific case where your literals are bracketed, using TAB on the lines in question gets what you want (because whitespace doesn’t play a role).

So what I’ve been doing in such cases is quickly recording a keyboard macro like <f3> C-n TAB <f4> as in F3, Ctrl-n (or down arrow), TAB, F4, and then using F4 repeatedly to apply the macro can save a couple of keystrokes. Or you can do C-u 10 C-x e to apply it 10 times.

(I know it doesn’t sound like much, but try re-indenting 100 lines of garbage literal without missing down-arrow, and then having to go up 5 lines and repeat things ;) ).


回答 5

我使用以下代码段。当选项卡处于非活动状态时,在选项卡上缩进当前行(通常如此);当选择处于非活动状态时,它将使整个区域向右缩进。

(defun my-python-tab-command (&optional _)
  "If the region is active, shift to the right; otherwise, indent current line."
  (interactive)
  (if (not (region-active-p))
      (indent-for-tab-command)
    (let ((lo (min (region-beginning) (region-end)))
          (hi (max (region-beginning) (region-end))))
      (goto-char lo)
      (beginning-of-line)
      (set-mark (point))
      (goto-char hi)
      (end-of-line)
      (python-indent-shift-right (mark) (point)))))
(define-key python-mode-map [remap indent-for-tab-command] 'my-python-tab-command)

I use the following snippet. On tab when the selection is inactive, it indents the current line (as it normally does); when the selection is inactive, it indents the whole region to the right.

(defun my-python-tab-command (&optional _)
  "If the region is active, shift to the right; otherwise, indent current line."
  (interactive)
  (if (not (region-active-p))
      (indent-for-tab-command)
    (let ((lo (min (region-beginning) (region-end)))
          (hi (max (region-beginning) (region-end))))
      (goto-char lo)
      (beginning-of-line)
      (set-mark (point))
      (goto-char hi)
      (end-of-line)
      (python-indent-shift-right (mark) (point)))))
(define-key python-mode-map [remap indent-for-tab-command] 'my-python-tab-command)

回答 6

交互进行缩进。

  1. 选择要缩进的区域。
  2. Cx TAB
  3. 使用箭头(<-->)进行交互缩进。
  4. Esc完成所需的缩进后,按三次。

从我的文章中复制:在Emacs中缩进几行

Do indentation interactively.

  1. Select the region to be indented.
  2. C-x TAB.
  3. Use arrows (<- and ->) to indent interactively.
  4. Press Esc three times when you are done with the required indentation.

Copied from my post in: Indent several lines in Emacs


回答 7

我普遍做这样的事情

;; intent whole buffer 
(defun iwb ()
  "indent whole buffer"
  (interactive)
  ;;(delete-trailing-whitespace)
  (indent-region (point-min) (point-max) nil)
  (untabify (point-min) (point-max)))

I do something like this universally

;; intent whole buffer 
(defun iwb ()
  "indent whole buffer"
  (interactive)
  ;;(delete-trailing-whitespace)
  (indent-region (point-min) (point-max) nil)
  (untabify (point-min) (point-max)))

如何使用Paramiko获取SSH返回码?

问题:如何使用Paramiko获取SSH返回码?

client = paramiko.SSHClient()
stdin, stdout, stderr = client.exec_command(command)

有什么方法可以获取命令返回码?

很难解析所有stdout / stderr并知道命令是否成功完成。

client = paramiko.SSHClient()
stdin, stdout, stderr = client.exec_command(command)

Is there any way to get the command return code?

It’s hard to parse all stdout/stderr and know whether the command finished successfully or not.


回答 0

SSHClient是一个简单的包装类,围绕着Paramiko中的更底层功能。该API文档列出recv_exit_status()的方法Channel类。

一个非常简单的演示脚本:

import paramiko
import getpass

pw = getpass.getpass()

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
client.connect('127.0.0.1', password=pw)

while True:
    cmd = raw_input("Command to run: ")
    if cmd == "":
        break
    chan = client.get_transport().open_session()
    print "running '%s'" % cmd
    chan.exec_command(cmd)
    print "exit status: %s" % chan.recv_exit_status()

client.close()

执行示例:

$ python sshtest.py
Password: 
Command to run: true
running 'true'
exit status: 0
Command to run: false
running 'false'
exit status: 1
Command to run: 
$

SSHClient is a simple wrapper class around the more lower-level functionality in Paramiko. The API documentation lists a recv_exit_status() method on the Channel class.

A very simple demonstration script:

import paramiko
import getpass

pw = getpass.getpass()

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
client.connect('127.0.0.1', password=pw)

while True:
    cmd = raw_input("Command to run: ")
    if cmd == "":
        break
    chan = client.get_transport().open_session()
    print "running '%s'" % cmd
    chan.exec_command(cmd)
    print "exit status: %s" % chan.recv_exit_status()

client.close()

Example of its execution:

$ python sshtest.py
Password: 
Command to run: true
running 'true'
exit status: 0
Command to run: false
running 'false'
exit status: 1
Command to run: 
$

回答 1

一个更简单的示例,该示例不涉及直接调用“较低级别”的通道类(即- 使用client.get_transport().open_session()命令):

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('blahblah.com')

stdin, stdout, stderr = client.exec_command("uptime")
print stdout.channel.recv_exit_status()    # status is 0

stdin, stdout, stderr = client.exec_command("oauwhduawhd")
print stdout.channel.recv_exit_status()    # status is 127

A much easier example that doesn’t involve invoking the “lower level” channel class directly (i.e. – NOT using the client.get_transport().open_session() command):

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('blahblah.com')

stdin, stdout, stderr = client.exec_command("uptime")
print stdout.channel.recv_exit_status()    # status is 0

stdin, stdout, stderr = client.exec_command("oauwhduawhd")
print stdout.channel.recv_exit_status()    # status is 127

回答 2

感谢JanC,我为示例添加了一些修改并在Python3中进行了测试,这对我来说真的很有用。

import paramiko
import getpass

pw = getpass.getpass()

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
#client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def start():
    try :
        client.connect('127.0.0.1', port=22, username='ubuntu', password=pw)
        return True
    except Exception as e:
        #client.close()
        print(e)
        return False

while start():
    key = True
    cmd = input("Command to run: ")
    if cmd == "":
        break
    chan = client.get_transport().open_session()
    print("running '%s'" % cmd)
    chan.exec_command(cmd)
    while key:
        if chan.recv_ready():
            print("recv:\n%s" % chan.recv(4096).decode('ascii'))
        if chan.recv_stderr_ready():
            print("error:\n%s" % chan.recv_stderr(4096).decode('ascii'))
        if chan.exit_status_ready():
            print("exit status: %s" % chan.recv_exit_status())
            key = False
            client.close()
client.close()

Thanks for JanC, I added some modification for the example and tested in Python3, it really useful for me.

import paramiko
import getpass

pw = getpass.getpass()

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
#client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def start():
    try :
        client.connect('127.0.0.1', port=22, username='ubuntu', password=pw)
        return True
    except Exception as e:
        #client.close()
        print(e)
        return False

while start():
    key = True
    cmd = input("Command to run: ")
    if cmd == "":
        break
    chan = client.get_transport().open_session()
    print("running '%s'" % cmd)
    chan.exec_command(cmd)
    while key:
        if chan.recv_ready():
            print("recv:\n%s" % chan.recv(4096).decode('ascii'))
        if chan.recv_stderr_ready():
            print("error:\n%s" % chan.recv_stderr(4096).decode('ascii'))
        if chan.exit_status_ready():
            print("exit status: %s" % chan.recv_exit_status())
            key = False
            client.close()
client.close()

回答 3

就我而言,输出缓冲是问题所在。由于存在缓冲,因此应用程序的输出不会以非阻塞方式输出。您可以在此处找到有关如何在不进行缓冲的情况下打印输出的答案:禁用输出缓冲。简而言之,只需使用-u选项运行python,如下所示:

> python -u script.py

In my case, output buffering was the problem. Because of buffering, the outputs from the application doesn’t come out non-blocking way. You can find the answer about how to print output without buffering in here: Disable output buffering. For short, just run python with -u option like this:

> python -u script.py


如何使用SCP或SSH将文件复制到Python中的远程服务器?

问题:如何使用SCP或SSH将文件复制到Python中的远程服务器?

我在本地计算机上有一个文本文件,该文件由cron中运行的每日Python脚本生成。

我想添加一些代码,以使该文件通过SSH安全地发送到我的服务器。

I have a text file on my local machine that is generated by a daily Python script run in cron.

I would like to add a bit of code to have that file sent securely to my server over SSH.


回答 0

您可以使用以下scp命令调用bash命令(它通过SSH复制文件)subprocess.run

import subprocess
subprocess.run(["scp", FILE, "USER@SERVER:PATH"])
#e.g. subprocess.run(["scp", "foo.bar", "joe@srvr.net:/path/to/foo.bar"])

如果您要创建要在同一Python程序中发送的文件,则需要在用于打开文件subprocess.run的代码with块之外调用命令(.close()如果不使用with块),因此您知道它已从Python刷新到磁盘。

您需要预先生成(在源计算机上)并安装(在目标计算机上)ssh密钥,以便scp自动通过您的公共ssh密钥进行身份验证(换句话说,因此您的脚本不需要输入密码) 。

You can call the scp bash command (it copies files over SSH) with subprocess.run:

import subprocess
subprocess.run(["scp", FILE, "USER@SERVER:PATH"])
#e.g. subprocess.run(["scp", "foo.bar", "joe@srvr.net:/path/to/foo.bar"])

If you’re creating the file that you want to send in the same Python program, you’ll want to call subprocess.run command outside the with block you’re using to open the file (or call .close() on the file first if you’re not using a with block), so you know it’s flushed to disk from Python.

You need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn’t ask for a password).


回答 1

要使用Paramiko库在Python中执行此操作(即不通过subprocess.Popen或类似程序包装scp),您将执行以下操作:

import os
import paramiko

ssh = paramiko.SSHClient() 
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, password=password)
sftp = ssh.open_sftp()
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()

(您可能希望处理未知的主机,错误,创建任何必要的目录等)。

To do this in Python (i.e. not wrapping scp through subprocess.Popen or similar) with the Paramiko library, you would do something like this:

import os
import paramiko

ssh = paramiko.SSHClient() 
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, password=password)
sftp = ssh.open_sftp()
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()

(You would probably want to deal with unknown hosts, errors, creating any directories necessary, and so on).


回答 2

您可能会使用subprocess模块。像这样:

import subprocess
p = subprocess.Popen(["scp", myfile, destination])
sts = os.waitpid(p.pid, 0)

destination形式可能在哪里user@remotehost:remotepath。感谢@Charles Duffy指出了我原始答案中的弱点,该答案使用单个字符串参数来指定scp操作shell=True-无法处理路径中的空格。

模块文档中提供了一些错误检查示例,您可能希望与此操作一起执行。

确保设置了正确的凭据,以便可以在计算机之间执行无人值守的无密码scp。已经有一个stackoverflow问题

You’d probably use the subprocess module. Something like this:

import subprocess
p = subprocess.Popen(["scp", myfile, destination])
sts = os.waitpid(p.pid, 0)

Where destination is probably of the form user@remotehost:remotepath. Thanks to @Charles Duffy for pointing out the weakness in my original answer, which used a single string argument to specify the scp operation shell=True – that wouldn’t handle whitespace in paths.

The module documentation has examples of error checking that you may want to perform in conjunction with this operation.

Ensure that you’ve set up proper credentials so that you can perform an unattended, passwordless scp between the machines. There is a stackoverflow question for this already.


回答 3

有两种方法可以解决此问题:

  1. 包装命令行程序
  2. 使用提供SSH功能的Python库(例如-ParamikoTwisted Conch

每种方法都有其自己的怪癖。如果要包装“ ssh”,“ scp”或“ rsync”之类的系统命令,则需要设置SSH密钥以启用无密码登录。您可以使用Paramiko或其他库将密码嵌入脚本中,但是您可能会发现缺少文档令人沮丧,尤其是如果您不熟悉SSH连接的基础知识(例如-密钥交换,代理等)时。不用说,对于这种事情,SSH密钥几乎总是比密码更好的主意。

注意:如果您打算通过SSH传输文件,则很难克服rsync,尤其是如果替代方法是普通的旧式scp。

我使用Paramiko的目的是替换系统调用,但由于其易用性和直接的熟悉性,我发现自己被包裹的命令所吸引。您可能有所不同。一段时间前,我给了海螺一次,但它对我没有吸引力。

如果选择系统调用路径,Python将提供一系列选项,例如os.system或命令/子进程模块。如果使用2.4+版本,我将使用子流程模块。

There are a couple of different ways to approach the problem:

  1. Wrap command-line programs
  2. use a Python library that provides SSH capabilities (eg – Paramiko or Twisted Conch)

Each approach has its own quirks. You will need to setup SSH keys to enable password-less logins if you are wrapping system commands like “ssh”, “scp” or “rsync.” You can embed a password in a script using Paramiko or some other library, but you might find the lack of documentation frustrating, especially if you are not familiar with the basics of the SSH connection (eg – key exchanges, agents, etc). It probably goes without saying that SSH keys are almost always a better idea than passwords for this sort of stuff.

NOTE: its hard to beat rsync if you plan on transferring files via SSH, especially if the alternative is plain old scp.

I’ve used Paramiko with an eye towards replacing system calls but found myself drawn back to the wrapped commands due to their ease of use and immediate familiarity. You might be different. I gave Conch the once-over some time ago but it didn’t appeal to me.

If opting for the system-call path, Python offers an array of options such as os.system or the commands/subprocess modules. I’d go with the subprocess module if using version 2.4+.


回答 4

达到了相同的问题,但不是“ hacking”或模拟命令行:

在这里找到这个答案。

from paramiko import SSHClient
from scp import SCPClient

ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('example.com')

with SCPClient(ssh.get_transport()) as scp:
    scp.put('test.txt', 'test2.txt')
    scp.get('test2.txt')

Reached the same problem, but instead of “hacking” or emulating command line:

Found this answer here.

from paramiko import SSHClient
from scp import SCPClient

ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('example.com')

with SCPClient(ssh.get_transport()) as scp:
    scp.put('test.txt', 'test2.txt')
    scp.get('test2.txt')

回答 5

您可以执行以下操作来处理主机密钥检查

import os
os.system("sshpass -p password scp -o StrictHostKeyChecking=no local_file_path username@hostname:remote_path")

You can do something like this, to handle the host key checking as well

import os
os.system("sshpass -p password scp -o StrictHostKeyChecking=no local_file_path username@hostname:remote_path")

回答 6

fabric 可用于通过ssh上传文件:

#!/usr/bin/env python
from fabric.api import execute, put
from fabric.network import disconnect_all

if __name__=="__main__":
    import sys
    # specify hostname to connect to and the remote/local paths
    srcdir, remote_dirname, hostname = sys.argv[1:]
    try:
        s = execute(put, srcdir, remote_dirname, host=hostname)
        print(repr(s))
    finally:
        disconnect_all()

fabric could be used to upload files vis ssh:

#!/usr/bin/env python
from fabric.api import execute, put
from fabric.network import disconnect_all

if __name__=="__main__":
    import sys
    # specify hostname to connect to and the remote/local paths
    srcdir, remote_dirname, hostname = sys.argv[1:]
    try:
        s = execute(put, srcdir, remote_dirname, host=hostname)
        print(repr(s))
    finally:
        disconnect_all()

回答 7

您可以使用为此目的专门设计的vassal软件包。

您只需要安装vassal并执行

from vassal.terminal import Terminal
shell = Terminal(["scp username@host:/home/foo.txt foo_local.txt"])
shell.run()

另外,这将节省您的身份验证凭据,而无需一次又一次地键入它们。

You can use the vassal package, which is exactly designed for this.

All you need is to install vassal and do

from vassal.terminal import Terminal
shell = Terminal(["scp username@host:/home/foo.txt foo_local.txt"])
shell.run()

Also, it will save you authenticate credential and don’t need to type them again and again.


回答 8

我使用sshfs通过ssh挂载远程目录,然后使用shutil复制文件:

$ mkdir ~/sshmount
$ sshfs user@remotehost:/path/to/remote/dst ~/sshmount

然后在python中:

import shutil
shutil.copy('a.txt', '~/sshmount')

此方法的优点是,如果要生成数据而不是本地缓存并发送单个大文件,则可以流式传输数据。

I used sshfs to mount the remote directory via ssh, and shutil to copy the files:

$ mkdir ~/sshmount
$ sshfs user@remotehost:/path/to/remote/dst ~/sshmount

Then in python:

import shutil
shutil.copy('a.txt', '~/sshmount')

This method has the advantage that you can stream data over if you are generating data rather than caching locally and sending a single large file.


回答 9

如果您不想使用SSL证书,请尝试以下操作:

import subprocess

try:
    # Set scp and ssh data.
    connUser = 'john'
    connHost = 'my.host.com'
    connPath = '/home/john/'
    connPrivateKey = '/home/user/myKey.pem'

    # Use scp to send file from local to host.
    scp = subprocess.Popen(['scp', '-i', connPrivateKey, 'myFile.txt', '{}@{}:{}'.format(connUser, connHost, connPath)])

except CalledProcessError:
    print('ERROR: Connection to host failed!')

Try this if you wan’t to use SSL certificates:

import subprocess

try:
    # Set scp and ssh data.
    connUser = 'john'
    connHost = 'my.host.com'
    connPath = '/home/john/'
    connPrivateKey = '/home/user/myKey.pem'

    # Use scp to send file from local to host.
    scp = subprocess.Popen(['scp', '-i', connPrivateKey, 'myFile.txt', '{}@{}:{}'.format(connUser, connHost, connPath)])

except CalledProcessError:
    print('ERROR: Connection to host failed!')

回答 10

使用外部资源paramiko;

    from paramiko import SSHClient
    from scp import SCPClient
    import os

    ssh = SSHClient() 
    ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
    ssh.connect(server, username='username', password='password')
    with SCPClient(ssh.get_transport()) as scp:
            scp.put('test.txt', 'test2.txt')

Using the external resource paramiko;

    from paramiko import SSHClient
    from scp import SCPClient
    import os

    ssh = SSHClient() 
    ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
    ssh.connect(server, username='username', password='password')
    with SCPClient(ssh.get_transport()) as scp:
            scp.put('test.txt', 'test2.txt')

回答 11

scp通过子进程调用命令不允许在脚本内接收进度报告。pexpect可用于提取该信息:

import pipes
import re
import pexpect # $ pip install pexpect

def progress(locals):
    # extract percents
    print(int(re.search(br'(\d+)%$', locals['child'].after).group(1)))

command = "scp %s %s" % tuple(map(pipes.quote, [srcfile, destination]))
pexpect.run(command, events={r'\d+%': progress})

查看局域网中的python复制文件(linux-> linux)

Calling scp command via subprocess doesn’t allow to receive the progress report inside the script. pexpect could be used to extract that info:

import pipes
import re
import pexpect # $ pip install pexpect

def progress(locals):
    # extract percents
    print(int(re.search(br'(\d+)%$', locals['child'].after).group(1)))

command = "scp %s %s" % tuple(map(pipes.quote, [srcfile, destination]))
pexpect.run(command, events={r'\d+%': progress})

See python copy file in local network (linux -> linux)


回答 12

一种非常简单的方法如下:

import os
os.system('sshpass -p "password" scp user@host:/path/to/file ./')

不需要python库(仅适用于os),它可以工作,但是使用此方法依赖于要安装的另一个ssh客户端。如果在另一个系统上运行,可能会导致不良行为。

A very simple approach is the following:

import os
os.system('sshpass -p "password" scp user@host:/path/to/file ./')

No python library are required (only os), and it works, however using this method relies on another ssh client to be installed. This could result in undesired behavior if ran on another system.


回答 13

有点骇人听闻,但以下方法可以工作:)

import os
filePath = "/foo/bar/baz.py"
serverPath = "/blah/boo/boom.py"
os.system("scp "+filePath+" user@myserver.com:"+serverPath)

Kind of hacky, but the following should work :)

import os
filePath = "/foo/bar/baz.py"
serverPath = "/blah/boo/boom.py"
os.system("scp "+filePath+" user@myserver.com:"+serverPath)

如何在python中进行scp?

问题:如何在python中进行scp?

在Python中scp文件的最pythonic方式是什么?我知道的唯一路线是

os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) )

这是一种hack,并且无法在类似Linux的系统之外运行,并且需要Pexpect模块的帮助来避免出现密码提示,除非您已经为远程主机设置了无密码的SSH。

我知道Twisted的conch,但我希望避免通过低级ssh模块自己实现scp。

我知道paramiko,支持SSH和SFTP的Python模块;但它不支持SCP。

背景:我正在连接到不支持SFTP但支持SSH / SCP的路由器,因此不能选择SFTP。

编辑:这是如何使用SCP或SSH将文件复制到Python中的远程服务器的重复项但是,该问题并未给出处理来自Python内部键的特定于scp的答案。我希望找到一种运行类似代码的方法

import scp

client = scp.Client(host=host, user=user, keyfile=keyfile)
# or
client = scp.Client(host=host, user=user)
client.use_system_keys()
# or
client = scp.Client(host=host, user=user, password=password)

# and then
client.transfer('/etc/local/filename', '/etc/remote/filename')

What’s the most pythonic way to scp a file in Python? The only route I’m aware of is

os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) )

which is a hack, and which doesn’t work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host.

I’m aware of Twisted’s conch, but I’d prefer to avoid implementing scp myself via low-level ssh modules.

I’m aware of paramiko, a Python module that supports SSH and SFTP; but it doesn’t support SCP.

Background: I’m connecting to a router which doesn’t support SFTP but does support SSH/SCP, so SFTP isn’t an option.

EDIT: This is a duplicate of How to copy a file to a remote server in Python using SCP or SSH?. However, that question doesn’t give an scp-specific answer that deals with keys from within Python. I’m hoping for a way to run code kind of like

import scp

client = scp.Client(host=host, user=user, keyfile=keyfile)
# or
client = scp.Client(host=host, user=user)
client.use_system_keys()
# or
client = scp.Client(host=host, user=user, password=password)

# and then
client.transfer('/etc/local/filename', '/etc/remote/filename')

回答 0

尝试使用ParamikoPython scp模块。它很容易使用。请参见以下示例:

import paramiko
from scp import SCPClient

def createSSHClient(server, port, user, password):
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(server, port, user, password)
    return client

ssh = createSSHClient(server, port, user, password)
scp = SCPClient(ssh.get_transport())

然后调用scp.get()scp.put()进行SCP操作。

SCPClient代码

Try the Python scp module for Paramiko. It’s very easy to use. See the following example:

import paramiko
from scp import SCPClient

def createSSHClient(server, port, user, password):
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(server, port, user, password)
    return client

ssh = createSSHClient(server, port, user, password)
scp = SCPClient(ssh.get_transport())

Then call scp.get() or scp.put() to do SCP operations.

(SCPClient code)


回答 1

您可能对尝试Pexpect源代码)感兴趣。这将使您能够处理交互式提示输入密码。

这是主要网站上的一些用法示例(用于ftp):

# This connects to the openbsd ftp site and
# downloads the recursive directory listing.
import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('noah@example.com')
child.expect ('ftp> ')
child.sendline ('cd pub')
child.expect('ftp> ')
child.sendline ('get ls-lR.gz')
child.expect('ftp> ')
child.sendline ('bye')

You might be interested in trying Pexpect (source code). This would allow you to deal with interactive prompts for your password.

Here’s a snip of example usage (for ftp) from the main website:

# This connects to the openbsd ftp site and
# downloads the recursive directory listing.
import pexpect
child = pexpect.spawn ('ftp ftp.openbsd.org')
child.expect ('Name .*: ')
child.sendline ('anonymous')
child.expect ('Password:')
child.sendline ('noah@example.com')
child.expect ('ftp> ')
child.sendline ('cd pub')
child.expect('ftp> ')
child.sendline ('get ls-lR.gz')
child.expect('ftp> ')
child.sendline ('bye')

回答 2

您也可以查看paramiko。还没有scp模块,但是它完全支持sftp。

[EDIT]抱歉,错过了提到paramiko的那一行。以下模块只是paramiko的scp协议的实现。如果您不想使用paramiko或conch(我知道用于python的唯一ssh实现),则可以对其进行重做以使用管道在常规ssh会话上运行。

scp.py for paramiko

You could also check out paramiko. There’s no scp module (yet), but it fully supports sftp.

[EDIT] Sorry, missed the line where you mentioned paramiko. The following module is simply an implementation of the scp protocol for paramiko. If you don’t want to use paramiko or conch (the only ssh implementations I know of for python), you could rework this to run over a regular ssh session using pipes.

scp.py for paramiko


回答 3

找不到直接的答案,并且此“ scp.Client”模块不存在。相反,适合我:

from paramiko import SSHClient
from scp import SCPClient

ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('example.com')

with SCPClient(ssh.get_transport()) as scp:
   scp.put('test.txt', 'test2.txt')
   scp.get('test2.txt')

Couldn’t find a straight answer, and this “scp.Client” module doesn’t exist. Instead, this suits me:

from paramiko import SSHClient
from scp import SCPClient

ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('example.com')

with SCPClient(ssh.get_transport()) as scp:
   scp.put('test.txt', 'test2.txt')
   scp.get('test2.txt')

回答 4

如果在win32上安装腻子,则会得到一个pscp(putty scp)。

因此您也可以在win32上使用os.system hack。

(并且您可以使用putty-agent进行密钥管理)


抱歉,这只是一个hack(但是您可以将其包装在python类中)

if you install putty on win32 you get an pscp (putty scp).

so you can use the os.system hack on win32 too.

(and you can use the putty-agent for key-managment)


sorry it is only a hack (but you can wrap it in a python class)


回答 5

您可以使用包子进程和命令调用来从外壳程序使用scp命令。

from subprocess import call

cmd = "scp user1@host1:files user2@host2:files"
call(cmd.split(" "))

You can use the package subprocess and the command call to use the scp command from the shell.

from subprocess import call

cmd = "scp user1@host1:files user2@host2:files"
call(cmd.split(" "))

回答 6

到目前为止,最好的解决方案可能是 AsyncSSH

https://asyncssh.readthedocs.io/en/latest/#scp-client

async with asyncssh.connect('host.tld') as conn:
    await asyncssh.scp((conn, 'example.txt'), '.', recurse=True)

As of today, the best solution is probably AsyncSSH

https://asyncssh.readthedocs.io/en/latest/#scp-client

async with asyncssh.connect('host.tld') as conn:
    await asyncssh.scp((conn, 'example.txt'), '.', recurse=True)

回答 7

看一下fabric.transfer

from fabric import Connection

with Connection(host="hostname", 
                user="admin", 
                connect_kwargs={"key_filename": "/home/myuser/.ssh/private.key"}
               ) as c:
    c.get('/foo/bar/file.txt', '/tmp/')

Have a look at fabric.transfer.

from fabric import Connection

with Connection(host="hostname", 
                user="admin", 
                connect_kwargs={"key_filename": "/home/myuser/.ssh/private.key"}
               ) as c:
    c.get('/foo/bar/file.txt', '/tmp/')

回答 8

自问这个问题以来已经有一段时间了,与此同时,另一个可以处理此问题的库也出现了:您可以使用Plumbum库中包含的复制功能:

import plumbum
r = plumbum.machines.SshMachine("example.net")
   # this will use your ssh config as `ssh` from shell
   # depending on your config, you might also need additional
   # params, eg: `user="username", keyfile=".ssh/some_key"`
fro = plumbum.local.path("some_file")
to = r.path("/path/to/destination/")
plumbum.path.utils.copy(fro, to)

It has been quite a while since this question was asked, and in the meantime, another library that can handle this has cropped up: You can use the copy function included in the Plumbum library:

import plumbum
r = plumbum.machines.SshMachine("example.net")
   # this will use your ssh config as `ssh` from shell
   # depending on your config, you might also need additional
   # params, eg: `user="username", keyfile=".ssh/some_key"`
fro = plumbum.local.path("some_file")
to = r.path("/path/to/destination/")
plumbum.path.utils.copy(fro, to)

回答 9

如果您使用* nix,则可以使用sshpass

sshpass -p password scp -o User=username -o StrictHostKeyChecking=no src dst:/path

If you are on *nix you can use sshpass

sshpass -p password scp -o User=username -o StrictHostKeyChecking=no src dst:/path

回答 10

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect('<IP Address>', username='<User Name>',password='' ,key_filename='<.PEM File path')

#Setup sftp connection and transmit this script 
print ("copying")

sftp = client.open_sftp() 
sftp.put(<Source>, <Destination>)


sftp.close()
import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

client.connect('<IP Address>', username='<User Name>',password='' ,key_filename='<.PEM File path')

#Setup sftp connection and transmit this script 
print ("copying")

sftp = client.open_sftp() 
sftp.put(<Source>, <Destination>)


sftp.close()

回答 11

嗯,也许另一个选择是使用sshfs之类的东西(Mac也有sshfs)。路由器安装后,您可以直接复制文件。我不确定这是否适用于您的特定应用程序,但这是一个方便的好方法。

Hmmm, perhaps another option would be to use something like sshfs (there an sshfs for Mac too). Once your router is mounted you can just copy the files outright. I’m not sure if that works for your particular application but it’s a nice solution to keep handy.


回答 12

不久前,我整理了一个依赖于paramiko的python SCP复制脚本。它包含用于处理与私钥或SSH密钥代理的连接以及后备密码验证的代码。

http://code.activestate.com/recipes/576810-copy-files-over-ssh-using-paramiko/

I while ago I put together a python SCP copy script that depends on paramiko. It includes code to handle connections with a private key or SSH key agent with a fallback to password authentication.

http://code.activestate.com/recipes/576810-copy-files-over-ssh-using-paramiko/


回答 13

我认为您可以轻松下载任何模块来实施scp,但是您可能会发现这很有用:http : //www.ibm.com/developerworks/linux/library/l-twist4.html

I don’t think there’s any one module that you can easily download to implement scp, however you might find this helpful: http://www.ibm.com/developerworks/linux/library/l-twist4.html


在python shell中按箭头键时看到转义字符

问题:在python shell中按箭头键时看到转义字符

在交互式python shell之类的shell中,通常可以使用箭头键在当前行中移动或获取先前的命令(使用向上箭头)等。

但是,当我将SSH切换到另一台机器并从python那里启动时,我得到如下会话:

>>> import os 
>>> ^[[A    

最后符来自上箭头。或者,使用左箭头:

>>> impor^[[D

我怎样才能解决这个问题?

在常规bash中,箭头键可以正常工作。奇怪的行为只是在交互式python(或perl等)shell中。

In shells like the interactive python shell, you can usually use the arrow keys to move around in the current line or get previous commands (with arrow-up) etc.

But after I ssh into another machine and start python there, I get sessions like:

>>> import os 
>>> ^[[A    

where the last character comes from arrow-up. Or, using arrow-left:

>>> impor^[[D

How can I fix this?

In the regular bash, arrow keys work fine. The weird behavior is just in the interactive python (or perl etc.) shell.


回答 0

似乎未启用readline。检查PYTHONSTARTUP变量是否已定义,对我而言,它指向/etc/pythonstart该文件,并且文件在交互之前由python进程执行,从而设置了读取行/历史记录处理。

感谢@chown,这里是有关此文档:http ://docs.python.org/2/tutorial/interactive.html

Looks like readline is not enabled. Check if PYTHONSTARTUP variable is defined, for me it points to /etc/pythonstart and that file is executed by the python process before going interactive, which setups readline/history handling.

Thanks to @chown here is the docs on this: http://docs.python.org/2/tutorial/interactive.html


回答 1

我已经通过安装readline软件包解决了这个问题:

pip install readline

I’ve solved this issue by installing readline package:

pip install readline

回答 2

在OS X上,我有不同的问题。

当我使用系统python shell时,键没有问题,但是virtualenv中有问题。我会尝试重新安装/升级virtualenv / readline,但未解决任何问题。

当我尝试使用import readline有问题的python shell时,收到以下错误消息:

ImportError: dlopen(/Users/raptor/.virtualenvs/bottle/lib/python2.7/lib-dynload/readline.so, 2): Library not loaded: /usr/local/opt/readline/lib/libreadline.6.dylib
Referenced from: /Users/raptor/.virtualenvs/bottle/lib/python2.7/lib-dynload/readline.so
Reason: image not found

因为有/usr/local/opt/readline/lib/libreadline.7.dylib但没有libreadline.6.dylib,所以我做了一个符号链接:

ln -s libreadline.7.dylib libreadline.6.dylib

问题已解决!

On OS X, I have different problem.

When I using system python shell, the keys is no problem, but problem in virtualenv. I’d try to reinstall/upgrade virtualenv/readline and nothing fixed.

While I try to import readline in problem python shell, get this error message:

ImportError: dlopen(/Users/raptor/.virtualenvs/bottle/lib/python2.7/lib-dynload/readline.so, 2): Library not loaded: /usr/local/opt/readline/lib/libreadline.6.dylib
Referenced from: /Users/raptor/.virtualenvs/bottle/lib/python2.7/lib-dynload/readline.so
Reason: image not found

Cause there is /usr/local/opt/readline/lib/libreadline.7.dylib but not libreadline.6.dylib, so I make a symbol link:

ln -s libreadline.7.dylib libreadline.6.dylib

Problem has been solved!


回答 3

在OS X上,Xcode更新有时会中断readline。解:

brew uninstall readline
brew upgrade python3
brew install readline
pip3 install readline

如果问题仍然存在,请尝试删除并readline使用pip安装它easy_install

pip3 uninstall readline
easy_install readline

On OS X, Xcode updates sometimes break readline. Solution:

brew uninstall readline
brew upgrade python3
brew install readline
pip3 install readline

If the problem still persists, try to remove readline using pip and install it using easy_install:

pip3 uninstall readline
easy_install readline

回答 4

在OS X上,使用python 3.5和virtualenv

$ pip install gnureadline

在解释器中执行以下操作:

import gnureadline

现在,箭头键应该可以正常工作。


附加信息…

请注意,自2015年10月1日起-readline已被弃用(来源https://github.com/ludwigschwardt/python-readline

改用gnureadline(请参阅:https : //github.com/ludwigschwardt/python-gnureadline

如果我使用python 3.5安装readline而不是gnureadline,则尝试导入解释器后收到错误消息:

>>> import readline
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: dlopen(/Users/pi/tmp/python-readline-test/.venv/lib/python3.5/readline.so, 2): Library not loaded: /usr/local/opt/readline/lib/libreadline.6.dylib
  Referenced from: /Users/pi/tmp/python-readline-test/.venv/lib/python3.5/readline.so
  Reason: image not found

On OS X, using python 3.5 and virtualenv

$ pip install gnureadline

In the interpreter do:

import gnureadline

Now arrow keys should work properly.


Additional information…

Note that as of Oct 1, 2015 – readline has been DEPRECATED (source https://github.com/ludwigschwardt/python-readline)

Use gnureadline instead (see: https://github.com/ludwigschwardt/python-gnureadline)

If I install readline instead of gnureadline using python 3.5, I receive errors after attempt to import in the interpreter:

>>> import readline
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: dlopen(/Users/pi/tmp/python-readline-test/.venv/lib/python3.5/readline.so, 2): Library not loaded: /usr/local/opt/readline/lib/libreadline.6.dylib
  Referenced from: /Users/pi/tmp/python-readline-test/.venv/lib/python3.5/readline.so
  Reason: image not found

回答 5

我最近遇到过这个问题,在阅读了很多有关pip install readline(不适用于mac osx)并且pip install gnureadline不满意之后,现在这是我的设置,该设置允许在任何python控制台中使用箭头键:

  1. 使用安装gnureadline pip install gnureadline

现在您可以执行操作,import gnureadline并且箭头键应该可以按预期工作。要使它们自动工作,请执行以下步骤:

  1. 创建(或附加到)文件~/.startup.pyimport gnureadline
  2. 追加到文件~/.bash_profileexport PYTHONSTARTUP=~/.startup.py

在我之前的设置中没有起作用的一件事是:在上自动导入gnureadline pdb.set_trace()。如果有人对这个问题有一个好的解决方案,我将不胜感激。

I have run into this issue recently and after reading a lot about pip install readline (does not work for mac osx) and pip install gnureadline and not being satisfied, this is now my setup which enables using arrow keys in any python console:

  1. install gnureadline using pip install gnureadline

now you can either do import gnureadline and arrow keys should work as expected. To make them work automatically follow the following steps:

  1. create (or append to) file ~/.startup.py: import gnureadline
  2. append to file ~/.bash_profile: export PYTHONSTARTUP=~/.startup.py

One thing that does not work, but did in my previous setup is: automatic import of gnureadline on pdb.set_trace(). If anyone has a good solution to this problem I would be grateful for a comment.


回答 6

  1. 安装readline-devel软件包。
  2. 用readline模块重新编译python
  3. 答对了!
  1. install readline-devel package.
  2. recompile python with readline module
  3. Bingo!

回答 7

我在Ubuntu 16.04 LTS上遇到Python 3.6.x的外壳历史记录(选项卡/箭头命令)问题。

Python 3.6.x是从源代码安装的。

对我来说解决的是使用以下命令行安装user12345所说的模块“ gnureadline”:

sudo pip3.6 install gnureadline

:)

I had problems with shell history(tab/arrows commands) of Python 3.6.x on Ubuntu 16.04 LTS.

Python 3.6.x was installed from source.

What solved for me was install the module “gnureadline” as said by user12345, using this command line:

sudo pip3.6 install gnureadline

:)


回答 8

这是在ubuntu 12.04 for python 3.3中为我工作的步骤。

1)打开终端并编写 sudo apt-get install libreadline-dev

2)从http://www.python.org/ftp/python/3.3.2/Python-3.3.2.tar.xz下载python 3.3.2的源文件

3)解压缩并导航到Shell中的Python-3.3.2 /目录

4)执行以下命令:

./configure
make
make test
sudo make install

Here are the steps which worked for me in ubuntu 12.04 for python 3.3.

1) open teminal and write sudo apt-get install libreadline-dev

2) download the source file of python 3.3.2 from http://www.python.org/ftp/python/3.3.2/Python-3.3.2.tar.xz

3) extract it and navigate to the Python-3.3.2/ directory in a shell

4) execute the following command:

./configure
make
make test
sudo make install

回答 9

将Mac升级到High Sierra后受到影响,这为我成功解决了它:

brew unlink python
xcode-select --install
brew install python

Was impacted after upgrading Mac to High Sierra, this successfully resolved it for me:

brew unlink python
xcode-select --install
brew install python

回答 10

在CentOS上,我通过

yum install readline-devel

然后重新编译python 3.4。

在OpenSUSE上,我通过

pip3 install readline

按照Valerio Crini的回答。

也许“ pip3 install readline”是一个通用解决方案。尚未在我的CentOS上尝试过。

On CentOS, I fix this by

yum install readline-devel

and then recompile python 3.4.

On OpenSUSE, I fix this by

pip3 install readline

following Valerio Crini’s answer.

Perhaps “pip3 install readline” is a general solution. Haven’t tried on my CentOS.


回答 11

我通过以下操作解决了这个问题:

  • 百胜安装readline-devel
  • 点安装readline

    • 我在这里遇到另一个错误:

      gcc: readline/libreadline.a: No such file or directory

      gcc: readline/libhistory.a: No such file or directory

      我通过安装解决了这个问题patch

      yum install patch

之后,我成功运行pip install readline,解决了我的python shell中的转义字符。

仅供参考,我正在使用RedHat

I fixed this by doing the following:

  • yum install readline-devel
  • pip install readline

    • I encountered another error here:

      gcc: readline/libreadline.a: No such file or directory

      gcc: readline/libhistory.a: No such file or directory

      I fixed this by installing patch:

      yum install patch

After that I managed to run pip install readline successfully which solved the escape characters in my python shell.

FYI, I’m using RedHat


回答 12

如果使用Anaconda Python,则可以通过运行以下命令解决此问题:

conda install readline

为我工作!

If you use Anaconda Python, you can fix this by running:

conda install readline

Worked for me!


回答 13

对于使用conda的用户,从conda-forge频道安装readline软件包将解决此问题:

conda install -c conda-forge readline=6.2

For those using conda, installing the readline package from conda-forge channel will fix the problem:

conda install -c conda-forge readline=6.2

回答 14

您是否使用-t参数调用ssh 来告诉ssh为您分配虚拟终端?

从手册页:

-t
强制伪tty分配。这可用于在远程计算机上执行任意基于屏幕的程序,这可能非常有用,例如在实现菜单服务时。即使ssh没有本地tty,多个-t选项也会强制tty分配。

另外,您可能还必须按照另一篇文章中的建议,在服务器上正确设置TERM环境变量。

Did you call ssh with the -t parameter to tell ssh to allocate a virtual terminal for you?

From the man page:

-t
Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.

Additionally you may also have to set the TERM environment variable on the server correctly as suggested in another post.


回答 15

在Mac OS X Mojave 10.14.6上,通过各种历史安装,brew我使用以下方法解决了此问题:

brew reinstall python2

鉴于每个人都有不同的安装方案,因此可能没有万灵药。我也尝试了上述方法,因此可能是一些答案的组合。Brew默认为默认值,python3因此,如果您安装了python2软件包,则还需要重新安装它。

On Mac OS X Mojave 10.14.6 with various historical installs via brew I solved this with:

brew reinstall python2

There is likely no magic bullet given everyone has a different install scenario. I tried the above as well so it may have been a combination of a few of the answers. Brew defaults to python3 so if you installed the python2 package it also needs to be reinstalled.


回答 16

这些答案都不适用于两个不同版本的Ubuntu。什么对我有用,但不是真正的解决办法,是将我的python代码包装在调用中rlwrap(可在ubuntu存储库中找到):

rlwrap python mycode.py

None of these answers worked for me on two different version of Ubuntu. What worked for me, but isn’t a true fix, is wrapping my python code in a call to rlwrap (available in the ubuntu repositories):

rlwrap python mycode.py


回答 17

您是否尝试过使用其他SSH客户端?某些SSH客户端具有用于不同远程进程的特殊内置键映射。我经常使用emacs遇到这一问题。

您正在使用什么客户端?我建议尝试使用Putty和SecureCRT来比较它们的行为。

Have you tried using a different SSH client? Some SSH clients have special, built-in keymappings for different remote processes. I ran into this one a lot with emacs.

What client are you using? I’d recommend trying Putty and SecureCRT to compare their behavior.


回答 18

readline模块已被弃用,这将在python shell中执行quit()或exit()时在最新的python版本中导致无效的指针错误。 pip install gnureadline代替

readline module has been deprecated which will cause invalid pointer error in latest python versions when executing quit() or exit() in python shell. pip install gnureadline instead


回答 19

当一切正常时,您的环境变量$ TERM如何设置?环境设置通常是解决此类问题的关键。

How’s your env variable $TERM set [a] when things work fine and [b] when they don’t? Env settings are often the key to such problems.


回答 20

尝试让密钥代码库在服务器上运行。如果这样不起作用,请尝试下载具有读键功能的库。

Try getting a key code library running on the server. If that does not work try to download a library with read-key ability.


回答 21

我试图在Ubuntu 14.0上构建Python 2.7。您将需要libreadline-dev。但是,如果从apt-get获取它,则当前版本为6.3,该版本与Python 2.7不兼容(不确定Python 3)。例如,在6.3版本中已删除了在readline的早期版本中定义的数据类型“ Function”和“ CPPFunction”,如下所示:

https://github.com/yyuu/pyenv/issues/126

也就是说,您需要获取早期版本的readline的源代码。我从apt-get中为该库安装了libreadline 5.2,并获得了头文件5.2的源代码。将它们放在/ usr / include中。

终于问题解决了。

I was trying build Python 2.7 on Ubuntu 14.0. You will need libreadline-dev. However, if you get it from apt-get, the current version is 6.3, which is incompatible with Python 2.7 (not sure about Python 3). For example, the data type “Function” and “CPPFunction”, which were defined in previous versions of readline has been removed in 6.3, as reported here:

https://github.com/yyuu/pyenv/issues/126

That is to say you need to get the source code of an earlier version of readline. I installed libreadline 5.2 from apt-get for the library, and get the source code of 5.2 for the header files. Put them in /usr/include.

Finally the issue has been resolved.


回答 22

在MacOsx上,我通过重新安装readline修复了此问题

brew reinstall readline

On MacOsx, I fixed this by reinstalling readline

brew reinstall readline

安装mysqldb python接口时找不到mysql_config

问题:安装mysqldb python接口时找不到mysql_config

我正在尝试使Python脚本在通过ssh连接到的Linux服务器上运行。该脚本使用mysqldb。我有我需要的所有其他组件,但是当我尝试通过setuptools安装mySQLdb时,如下所示:

python setup.py install

我得到以下与mysql_config命令有关的错误报告。

sh: mysql_config: command not found
Traceback (most recent call last):
  File "setup.py", line 15, in <module>
    metadata, options = get_config()
  File "/usr/lib/python2.5/MySQL-python-1.2.3/setup_posix.py", line 43, in get_config
    libs = mysql_config("libs_r")
  File "/usr/lib/python2.5/MySQL-python-1.2.3/setup_posix.py", line 24, in mysql_config
    raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found

还有其他人遇到此错误吗?如果是,您如何解决该错误/我该怎么做才能成功安装mysqldb?

I am trying to get a Python script to run on the linux server I’m connected to via ssh. The script uses mysqldb. I have all the other components I need, but when I try to install mySQLdb via setuptools like so:,

python setup.py install

I get the following error report related to the mysql_config command.

sh: mysql_config: command not found
Traceback (most recent call last):
  File "setup.py", line 15, in <module>
    metadata, options = get_config()
  File "/usr/lib/python2.5/MySQL-python-1.2.3/setup_posix.py", line 43, in get_config
    libs = mysql_config("libs_r")
  File "/usr/lib/python2.5/MySQL-python-1.2.3/setup_posix.py", line 24, in mysql_config
    raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found

Has anyone else encountered this error and if so how did you resolve it/what can I do to successfully install mysqldb?


回答 0

mySQLdb是mysql的python接口,但不是mysql本身。显然,mySQLdb需要命令“ mysql_config”,因此您需要先安装该命令。

您可以通过从shell运行“ mysql”来确认自己是否安装了mysql吗?这应该给您一个响应,而不是“ mysql:not found”。

您使用的是哪个Linux发行版?Mysql已为大多数Linux发行版预先打包。例如,对于debian / ubuntu,安装mysql就像

sudo apt-get install mysql-server

mysql-config位于不同的软件包中,可以从安装(同样,假设debian / ubuntu):

sudo apt-get install libmysqlclient-dev

如果您使用的是mariadb,请替换为mysql,然后运行

sudo apt-get install libmariadbclient-dev

参考:https : //github.com/JudgeGirl/Judge-sender/issues/4#issuecomment-186542797

mySQLdb is a python interface for mysql, but it is not mysql itself. And apparently mySQLdb needs the command ‘mysql_config’, so you need to install that first.

Can you confirm that you did or did not install mysql itself, by running “mysql” from the shell? That should give you a response other than “mysql: command not found”.

Which linux distribution are you using? Mysql is pre-packaged for most linux distributions. For example, for debian / ubuntu, installing mysql is as easy as

sudo apt-get install mysql-server

mysql-config is in a different package, which can be installed from (again, assuming debian / ubuntu):

sudo apt-get install libmysqlclient-dev

if you are using mariadb, the drop in replacement for mysql, then run

sudo apt-get install libmariadbclient-dev

Reference: https://github.com/JudgeGirl/Judge-sender/issues/4#issuecomment-186542797


回答 1

我正在python-mysql使用以下命令在Ubuntu 12.04上安装

pip install mysql-python

首先,我有同样的问题:

Not Found "mysql_config"

这对我有用

$ sudo apt-get install libmysqlclient-dev

然后我有这个问题:

...
_mysql.c:29:20: error fatal: Python.h: No existe el archivo o el directorio

compilación terminada.

error: command 'gcc' failed with exit status 1

然后我尝试了

apt-get install python-dev

然后我很高兴:)

pip install mysql-python
    Installing collected packages: mysql-python
      Running setup.py install for mysql-python
        building '_mysql' extension
        gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,4,'beta',4) -D__version__=1.2.4b4 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -g
        In file included from _mysql.c:44:0:
        /usr/include/mysql/my_config.h:422:0: aviso: se redefinió "HAVE_WCSCOLL" [activado por defecto]
        /usr/include/python2.7/pyconfig.h:890:0: nota: esta es la ubicación de la definición previa
        gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-x86_64-2.7/_mysql.o -L/usr/lib/x86_64-linux-gnu -lmysqlclient_r -lpthread -lz -lm -lrt -ldl -o build/lib.linux-x86_64-2.7/_mysql.so

Successfully installed mysql-python
Cleaning up...

I was installing python-mysql on Ubuntu 12.04 using

pip install mysql-python

First I had the same problem:

Not Found "mysql_config"

This worked for me

$ sudo apt-get install libmysqlclient-dev

Then I had this problem:

...
_mysql.c:29:20: error fatal: Python.h: No existe el archivo o el directorio

compilación terminada.

error: command 'gcc' failed with exit status 1

Then I tried with

apt-get install python-dev

And then I was happy :)

pip install mysql-python
    Installing collected packages: mysql-python
      Running setup.py install for mysql-python
        building '_mysql' extension
        gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,4,'beta',4) -D__version__=1.2.4b4 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -g
        In file included from _mysql.c:44:0:
        /usr/include/mysql/my_config.h:422:0: aviso: se redefinió "HAVE_WCSCOLL" [activado por defecto]
        /usr/include/python2.7/pyconfig.h:890:0: nota: esta es la ubicación de la definición previa
        gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-x86_64-2.7/_mysql.o -L/usr/lib/x86_64-linux-gnu -lmysqlclient_r -lpthread -lz -lm -lrt -ldl -o build/lib.linux-x86_64-2.7/_mysql.so

Successfully installed mysql-python
Cleaning up...

回答 2

(特定于Mac OS X)

我做了很多尝试,但是这些命令最终对我有用。

  1. 安装 mysql
    brew install mysql
  2. brew unlink mysql
  3. brew install mysql-connector-c
  4. 将mysql bin文件夹添加到PATH
    export PATH=/usr/local/Cellar/mysql/8.0.11/bin:$PATH
  5. mkdir /usr/local/Cellar/lib/
  6. 创建一个符号链接
    sudo ln -s /usr/local/Cellar/mysql/8.0.11/lib/libmysqlclient.21.dylib /usr/local/Cellar/lib/libmysqlclient.21.dylib
  7. brew reinstall openssl来源
  8. 最后,安装mysql-client
    LIBRARY_PATH=$LIBRARY_PATH:/usr/local/opt/openssl/lib/ pip install mysqlclient

更新:如果此方法不起作用,@ vinyll建议brew link mysql在步骤8之前运行。

(Specific to Mac OS X)

I have tried a lot of things, but these set of commands finally worked for me.

  1. Install mysql
    brew install mysql
    
  2. brew unlink mysql
  3. brew install mysql-connector-c
  4. Add the mysql bin folder to PATH
    export PATH=/usr/local/Cellar/mysql/8.0.11/bin:$PATH
    
  5. mkdir /usr/local/Cellar/lib/
  6. Create a symlink
    sudo ln -s /usr/local/Cellar/mysql/8.0.11/lib/libmysqlclient.21.dylib /usr/local/Cellar/lib/libmysqlclient.21.dylib
    
  7. brew reinstall openssl (source)
  8. Finally, install mysql-client
    LIBRARY_PATH=$LIBRARY_PATH:/usr/local/opt/openssl/lib/ pip install mysqlclient
    

Update: In case this doesn’t work, @vinyll suggests to run brew link mysql before step 8.


回答 3

在红帽上,我不得不做

sudo yum install mysql-devel gcc gcc-devel python-devel
sudo easy_install mysql-python

然后它起作用了。

On Red Hat I had to do

sudo yum install mysql-devel gcc gcc-devel python-devel
sudo easy_install mysql-python

Then it worked.


回答 4

以下内容适用于Ubuntu 12.04 LTS:

apt-get install libmysqlclient-dev python-dev

尽管一切正常,但我仍然继续执行以下操作:

export PATH=$PATH:/usr/local/mysql/bin/

The below worked for me on Ubuntu 12.04 LTS:

apt-get install libmysqlclient-dev python-dev

All though it worked, i still went ahead to do the below:

export PATH=$PATH:/usr/local/mysql/bin/

回答 5

尝试安装时出现相同的错误mysql-python

这就是我修复它的方式。

sudo PATH=/usr/local/mysql/bin/:$PATH pip install mysql-python

问题是安装程序无法在默认路径中找到mysql_config。现在它可以..并且有效..

 15 warnings generated.
    clang -bundle -undefined dynamic_lookup -Wl,-F. build/temp.macosx-10.8-intel-2.7/_mysql.o -L/usr/local/mysql/lib -lmysqlclient_r -lz -lm -lmygcc -o build/lib.macosx-10.8-intel-2.7/_mysql.so -arch x86_64

Successfully installed mysql-python
Cleaning up...

希望这可以帮助。

谢谢。

I got the same error while trying to install mysql-python.

This is how I fixed it.

sudo PATH=/usr/local/mysql/bin/:$PATH pip install mysql-python

The problem was that the installer could not find the mysql_config in the default path. Now it can ..and it worked..

 15 warnings generated.
    clang -bundle -undefined dynamic_lookup -Wl,-F. build/temp.macosx-10.8-intel-2.7/_mysql.o -L/usr/local/mysql/lib -lmysqlclient_r -lz -lm -lmygcc -o build/lib.macosx-10.8-intel-2.7/_mysql.so -arch x86_64

Successfully installed mysql-python
Cleaning up...

Hope this helps.

Thanks.


回答 6

我通过以下步骤解决了此问题:

sudo apt-get install libmysqlclient-dev
sudo apt-get install python-dev
sudo python setup.py install

I fixed this problem with the following steps:

sudo apt-get install libmysqlclient-dev
sudo apt-get install python-dev
sudo python setup.py install

回答 7

命令(也是mysql)mPATH可能丢失。

export PATH=$PATH:/usr/local/mysql/bin/

The commands (mysql too) mPATH might be missing.

export PATH=$PATH:/usr/local/mysql/bin/


回答 8

步骤1:-同时安装Python3和Python3-dev

sudo apt-get install python3 python3-dev

步骤2:- 安装Python和Mysql连接器

sudo apt-get install libmysqlclient-dev

步骤3:- 安装python mysql客户端

sudo apt-get install mysqlclient

这将解决您的问题

Step1:-Install Python3 & Python3-dev Both

sudo apt-get install python3 python3-dev

Step2:- Install Python & Mysql Connector

sudo apt-get install libmysqlclient-dev

step3:- Install python mysql client

sudo apt-get install mysqlclient

This will Solve your Problem


回答 9

如果您使用的是macOS,并且已经通过brew install安装了mysql@5.7,请执行以下操作:

  1. brew install mysql-connector-c
  2. brew unlink mysql@5.7
  3. brew link --overwrite --dry-run mysql@5.7 首先,查看哪些符号链接被覆盖
  4. brew link --overwrite --force mysql@5.7 用mysql@5.7实际覆盖与mysql相关的符号链接
  5. pip install mysqlclient

If you’re on macOS and already installed mysql@5.7 via brew install:

  1. brew install mysql-connector-c
  2. brew unlink mysql@5.7
  3. brew link --overwrite --dry-run mysql@5.7 first, to see what symlinks are getting overwritten
  4. brew link --overwrite --force mysql@5.7 to actually overwrite mysql-related symlinks with mysql@5.7
  5. pip install mysqlclient

回答 10

我通过安装libmysqlclient来修复它:

sudo apt-get install libmysqlclient16-dev

I fixed it by installing libmysqlclient:

sudo apt-get install libmysqlclient16-dev

回答 11

MySQL-python软件包正在使用该mysql_config命令来了解mysql主机上的配置。您的主机没有该mysql_config命令。

来自dev.mysql.com的MySQL开发库程序包(MySQL-devel-xxx)提供了此命令以及MySQL-python程序包所需的库。MySQL-devel可在下载-社区服务器区域中找到这些软件包。MySQL开发库软件包名称MySQL-devel以MySQL版本和linux平台(例如MySQL-devel-5.5.24-1.linux2.6.x86_64.rpm)为基础,并有所不同。

注意,您不需要安装mysql服务器。

The MySQL-python package is using the mysql_config command to learn about the mysql configuration on your host. Your host does not have the mysql_config command.

The MySQL development libraries package (MySQL-devel-xxx) from dev.mysql.com provides this command and the libraries needed by the MySQL-python package. The MySQL-devel packages are found in the download – community server area. The MySQL development library package names start with MySQL-devel and vary based MySQL version and linux platform (e.g. MySQL-devel-5.5.24-1.linux2.6.x86_64.rpm.)

Note that you do not need to install mysql server.


回答 12

不建议使用libmysqlclient-dev软件包,因此请使用以下命令对其进行修复。

软件包libmysqlclient-dev不可用,但是由另一个软件包引用。这可能意味着该软件包已丢失,已被废弃或只能从其他来源获得

sudo apt-get install default-libmysqlclient-dev

The package libmysqlclient-dev is deprecated, so use the below command to fix it.

Package libmysqlclient-dev is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source

sudo apt-get install default-libmysqlclient-dev

回答 13

在centos 7中,这对我有用:

yum install mariadb-devel
pip install mysqlclient

In centos 7 this works for me :

yum install mariadb-devel
pip install mysqlclient

回答 14

在我的Fedora 23机器上,我必须运行以下命令:

sudo dnf install mysql-devel

On my Fedora 23 machine I had to run the following:

sudo dnf install mysql-devel

回答 15

对于Alpine Linux:

$ apk add mariadb-dev mariadb-client mariadb-libs

MariaDB是MySQL的直接替代品,并成为Alpine 3.2的新标准。参见https://bugs.alpinelinux.org/issues/4264

For Alpine Linux:

$ apk add mariadb-dev mariadb-client mariadb-libs

MariaDB is a drop-in replacement for MySQL and became the new standard as of Alpine 3.2. See https://bugs.alpinelinux.org/issues/4264


回答 16

我认为,以下几行可以在终端上执行

 sudo ln -s /usr/local/zend/mysql/bin/mysql_config /usr/sbin/

该mysql_config目录用于MacOSx上的zend服务器。您可以像下面的几行一样在linux上做

sudo ln -s /usr/local/mysql/bin/mysql_config /usr/sbin/

这是默认的Linux mysql目录。

I think, following lines can be executed on terminal

 sudo ln -s /usr/local/zend/mysql/bin/mysql_config /usr/sbin/

This mysql_config directory is for zend server on MacOSx. You can do it for linux like following lines

sudo ln -s /usr/local/mysql/bin/mysql_config /usr/sbin/

This is default linux mysql directory.


回答 17

我遇到了这个问题,并通过将符号链接添加到来解决mysql_config

我已经用自制软件安装了mysql,并在输出中看到了这一点。

Error: The `brew link` step did not complete successfully

根据您的购买方式,mysql它会出现在不同的地方。以我为例,/usr/local/Cellar/mysql
一旦您知道它在哪里,就应该可以建立一个指向python寻找位置的符号链接。 /usr/local/mysql

这对我有用。

ln -s /usr/local/Cellar/mysql/<< VERSION >>/bin/mysql_config   /usr/local/mysql/bin/mysql_config

I had this issues and solved if by adding a symlink to mysql_config.

I had installed mysql with homebrew and saw this in the output.

Error: The `brew link` step did not complete successfully

Depending on how you got mysql it will be in different places. In my case /usr/local/Cellar/mysql
Once you know where it is you should be able to ma a symbolic link to where python is looking for it. /usr/local/mysql

This worked for me.

ln -s /usr/local/Cellar/mysql/<< VERSION >>/bin/mysql_config   /usr/local/mysql/bin/mysql_config

回答 18

我有同样的问题。我通过按照本教程在Ubuntu 16.04上使用python3-dev安装Python的方式解决了问题:

sudo apt-get update
sudo apt-get -y upgrade
sudo apt-get install -y python3-pip
sudo apt-get install build-essential libssl-dev libffi-dev python3-dev

现在您可以设置虚拟环境:

sudo apt-get install -y python3-venv
pyvenv my_env
source my_env/bin/activate

I had the same problem. I solved it by following this tutorial to install Python with python3-dev on Ubuntu 16.04:

sudo apt-get update
sudo apt-get -y upgrade
sudo apt-get install -y python3-pip
sudo apt-get install build-essential libssl-dev libffi-dev python3-dev

And now you can set up your virtual environment:

sudo apt-get install -y python3-venv
pyvenv my_env
source my_env/bin/activate

回答 19

您需要安装python-dev软件包:

sudo apt-get install python-dev

You need to install the python-dev package:

sudo apt-get install python-dev

回答 20

须藤apt-get install python-mysqldb

Python 2.5?听起来您正在使用非常旧的Ubuntu Server版本(Hardy 8.04?)-请确认服务器使用的Linux版本。

在ubuntu软件包数据库上搜索python-mysql

一些其他信息:

从mysql-python的自述文件-

红帽Linux ………….

MySQL-python已预包装在Red Hat Linux 7.x和更高版本中。这包括Fedora Core和Red Hat Enterprise Linux。您还可以如上所述构建自己的RPM软件包。

Debian GNU / Linux …………….

打包为python-mysqldb_ ::

# apt-get install python-mysqldb

或使用Synaptic。

.. _ python-mysqldbhttp : //packages.debian.org/python-mysqldb

Ubuntu ……

与Debian相同。

脚注:如果您确实使用的服务器发行版早于Ubuntu 10.04,则您不受官方支持,因此应尽快升级。

sudo apt-get install python-mysqldb

Python 2.5? Sounds like you are using a very old version of Ubuntu Server (Hardy 8.04?) – please confirm which Linux version the server uses.

python-mysql search on ubuntu package database

Some additional info:

From the README of mysql-python –

Red Hat Linux ………….

MySQL-python is pre-packaged in Red Hat Linux 7.x and newer. This includes Fedora Core and Red Hat Enterprise Linux. You can also build your own RPM packages as described above.

Debian GNU/Linux …………….

Packaged as python-mysqldb_::

# apt-get install python-mysqldb

Or use Synaptic.

.. _python-mysqldb: http://packages.debian.org/python-mysqldb

Ubuntu ……

Same as with Debian.

Footnote: If you really are using a server distribution older than Ubuntu 10.04 then you are out of official support, and should upgrade sooner rather than later.


回答 21

该方法仅适用于那些知道已安装Mysql但仍找不到mysql_config的用户。如果python安装无法在系统路径中找到mysql_config,则会发生这种情况,如果通过.dmg Mac Package完成安装或在某个自定义路径中进行安装,则通常会发生这种情况。MySqlDB最简单且记录在案的方法是更改site.cfg。找到可能位于/ usr / local / mysql / bin /中的mysql_config,然后像下面那样更改变量mysql_config,然后再次运行安装。不要忘记通过删除“#”取消注释

在行下更改

“ #mysql_config = / usr / local / bin / mysql_config”

“ mysql_config = / usr / local / mysql / bin / mysql_config”

取决于系统中的路径。

顺便说一句,我在更改site.cfg之后使用python安装

sudo /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python setup.py安装

This method is only for those who know that Mysql is installed but still mysql_config can’t be find. This happens if python install can’t find mysql_config in your system path, which mostly happens if you have done the installation via .dmg Mac Package or installed at some custom path. The easiest and documented way by MySqlDB is to change the site.cfg. Find the mysql_config which is probably in /usr/local/mysql/bin/ and change the variable namely mysql_config just like below and run the installation again. Don’t forget to un-comment it by removing “#”

Change below line

“#mysql_config = /usr/local/bin/mysql_config”

to

“mysql_config = /usr/local/mysql/bin/mysql_config”

depending upon the path in your system.

By the way I used python install after changing the site.cfg

sudo /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python setup.py install


回答 22

到目前为止,所有解决方案(Linux)都需要具有sudoroot用户权限才能安装。如果您没有root权限且没有root权限,则这是一个解决方案sudo。(否sudo apt install ...):

  1. 从此镜像下载libmysqlclient-dev的.deb文件
  2. 导航到下载的文件并运行。dpkg -x libmysqlclient-dev_<version tag>.deb .这将提取一个名为的文件夹usr
  3. 符号链接./usr/bin/mysql_config到您的上找到的某个位置$PATH

    ln -s `pwd` /usr/bin/mysql_config FOLDER_IN_YOUR_PATH

  4. 现在应该可以找到 mysql_config

在Ubuntu 18.04上测试。

So far, all solutions (Linux) require sudo or root rights to install . Here is a solution if you do not have root rights and without sudo. (no sudo apt install ...):

  1. Download the .deb file of the libmysqlclient-dev, e.g. from this mirror
  2. Navigate to the downloaded file and run dpkg -x libmysqlclient-dev_<version tag>.deb . This will extract a folder called usr.
  3. Symlink ./usr/bin/mysql_config to somewhere that is found on your $PATH:

    ln -s `pwd` /usr/bin/mysql_config FOLDER_IN_YOUR_PATH

  4. It should now be able to find mysql_config

Tested on Ubuntu 18.04.


回答 23

对于macOS Mojave,需要附加配置,编译器才能找到openssl,您可能需要设置:

export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"

For macOS Mojave , additional configuration was required, for compilers to find openssl you may need to set:

export LDFLAGS="-L/usr/local/opt/openssl/lib"
export CPPFLAGS="-I/usr/local/opt/openssl/include"

回答 24

我认为在2020年解决此问题的最便捷方法是使用另一个python软件包。我们不需要安装任何其他二进制软件。

尝试这个

pip install mysql-connector-python

然后

import mysql.connector

mydb = mysql.connector.connect(
          host="",
          user="",
          passwd="",
          database=""
          )      
cursor = mydb.cursor( buffered=True)
cursor.execute('show tables;')
cursor.execute('insert into test values (null, "a",10)')
mydb.commit()
mydb.disconnect()

I think the most convenient way to solve this problem in 2020 is using another python package. We don’t need install any other binary software.

Try this

pip install mysql-connector-python

and then

import mysql.connector

mydb = mysql.connector.connect(
          host="",
          user="",
          passwd="",
          database=""
          )      
cursor = mydb.cursor( buffered=True)
cursor.execute('show tables;')
cursor.execute('insert into test values (null, "a",10)')
mydb.commit()
mydb.disconnect()

回答 25

我遇到了同样的问题,只是将* mysql_config *所在的路径添加到环境变量PATH中,它对我有用。

I encountered the same problem, just added the path where *mysql_config* resided to the environment variable PATH and it worked for me.


回答 26

sudo apt-get build-dep python-mysqldb 将安装所有依赖项以从PIP / easy_install构建软件包

sudo apt-get build-dep python-mysqldb will install all the dependencies to build the package from PIP/easy_install


回答 27

由于实际错误是

gcc ... -I/usr/include/python2.7 ...

_mysql.c:29:20: error: Python.h: No such file or directory

并且如果您无法安装python-dev或python-devel软件包,则可以从http://hg.python.org/下载包含所需版本的python源的存档,并将标头文件放置在正确的文件夹中,以包含

As actual error is

gcc ... -I/usr/include/python2.7 ...

_mysql.c:29:20: error: Python.h: No such file or directory

and If you can’t install python-dev or python-devel packages, you may download archive with needed version of python sources from http://hg.python.org/ and place headers files in proper folder for include


回答 28

只需输入:

$ sudo apt-get install python-dev
$ venv/bin/pip install MySQL-python

这样可以解决这个问题。

Just type:

$ sudo apt-get install python-dev
$ venv/bin/pip install MySQL-python

This will solve this problems.


回答 29

在CentOS 7中,应执行以下操作:

#step1:install mysql 
https://dev.mysql.com/doc/mysql-yum-repo-quick-guide/en/

#step2:
sudo yum install mysql-devel

In CentOS 7 , the following things should be done:

#step1:install mysql 
https://dev.mysql.com/doc/mysql-yum-repo-quick-guide/en/

#step2:
sudo yum install mysql-devel

Borg-使用压缩和身份验证加密对服务器执行数据消除

更多截屏视频:installationadvanced usage

什么是BorgBackup?

BorgBackup(简称:Borg)是一个重复数据消除备份程序。或者,它支持压缩和经过身份验证的加密

Borg的主要目标是提供一种高效、安全的数据备份方式。由于只存储更改,因此使用的重复数据消除技术使Borg适用于日常备份。经过身份验证的加密技术使其适用于备份到不完全受信任的目标

请参阅installation manual或者,如果您已经下载了Borg,docs/installation.rst开始学习博格。还有一个offline documentation可用,有多种格式

主要特点

节省空间的存储
基于内容定义的区块的重复数据消除用于减少存储的字节数:每个文件被拆分成多个可变长度的区块,并且只有以前从未见过的区块才会添加到存储库中

如果一个块的id_hash值相同,则认为它是重复的。密码强散列或MAC函数用作id_hash,例如(HMAC-)sha256

要执行重复数据消除,将考虑同一存储库中的所有区块,无论它们来自不同的计算机、来自以前的备份、来自相同的备份,甚至来自相同的单个文件

与其他重复数据消除方法相比,此方法不依赖于:

  • 文件/目录名称保持不变:因此,即使在共享回收站的计算机之间,您也可以在不影响重复数据删除的情况下四处移动数据
  • 完整的文件或时间戳保持不变:如果大文件稍有更改,则只需存储几个新的区块-这对虚拟机或原始磁盘非常有用
  • 数据块在文件内的绝对位置:填充可能会发生移位,但重复数据消除算法仍会找到该位置
速度
  • 性能关键型代码(分块、压缩、加密)是用C/Cython实现的
  • 文件/块索引数据的本地缓存
  • 快速检测未修改的文件
数据加密
所有数据均可使用256位AES加密进行保护,数据完整性和真实性使用HMAC-SHA256进行验证。数据是加密的客户端
模糊处理
可选地,Borg可以主动地模糊例如文件/块的大小,以使指纹攻击更加困难
压缩
可以选择压缩所有数据:
  • LZ4(超高速、低压缩)
  • zstd(从高速低压缩到高压缩低速的大范围)
  • zlib(中速和压缩)
  • LZMA(低速、高压缩)
异地备份
Borg可以将数据存储在可通过SSH访问的任何远程主机上。如果在远程主机上安装了Borg,与使用网络文件系统(sshfs、nfs、.)相比,可以获得很大的性能提升。
可装载为文件系统的备份
备份归档可作为用户空间文件系统挂载,以便轻松进行交互式备份检查和恢复(例如,使用常规文件管理器)
在多个平台上轻松安装
我们提供不需要安装任何内容的单文件二进制文件-您只需在以下平台上运行它们:
  • Linux操作系统
  • Mac OS X
  • FreeBSD
  • OpenBSD和NetBSD(尚不支持xattrs/ACL或二进制文件)
  • Cygwin(试验性的,目前还没有二进制文件)
  • Windows 10的Linux子系统(实验性)
自由开放源码软件
  • 安全性和功能可以独立审核
  • 在BSD(3条款)许可下获得许可,请参阅License获取完整的许可证

易于使用

初始化新的备份存储库(请参见borg init --help对于加密选项):

$ borg init -e repokey /path/to/repo

创建备份存档:

$ borg create /path/to/repo::Saturday1 ~/Documents

现在再做一次备份,只是为了炫耀一下伟大的重复数据消除功能:

$ borg create -v --stats /path/to/repo::Saturday2 ~/Documents
-----------------------------------------------------------------------------
Archive name: Saturday2
Archive fingerprint: 622b7c53c...
Time (start): Sat, 2016-02-27 14:48:13
Time (end):   Sat, 2016-02-27 14:48:14
Duration: 0.88 seconds
Number of files: 163
-----------------------------------------------------------------------------
               Original size      Compressed size    Deduplicated size
This archive:        6.85 MB              6.85 MB             30.79 kB  <-- !
All archives:       13.69 MB             13.71 MB              6.88 MB

               Unique chunks         Total chunks
Chunk index:             167                  330
-----------------------------------------------------------------------------

有关图形前端,请参阅我们的补充项目BorgWeb

帮助,捐款,施舍,成为赞助人

我们随时欢迎您的帮助!

传播信息、提供反馈、帮助编写文档、测试或开发

你也可以给这个项目提供资金支持,详情请看那里:

https://www.borgbackup.org/support/fund.html

链接

兼容性说明

预计当主要版本号更改时(如从0.x.y到1.0.0或从1.x.y到2.0.0),我们会反复破坏兼容性

未发布的开发版本具有未知的兼容性属性

这是正在开发的软件,您自己决定它是否适合您的需求

安全问题应报告给Security contact(或参阅docs/support.rst在源代码分发中)