我正在使用此代码从外部程序获取标准输出:
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
Run Code Online (Sandbox Code Playgroud)
communic()方法返回一个字节数组:
>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
Run Code Online (Sandbox Code Playgroud)
但是,我想将输出作为普通的Python字符串.所以我可以这样打印:
>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
Run Code Online (Sandbox Code Playgroud)
我认为这是binascii.b2a_qp()方法的用途,但是当我尝试它时,我又得到了相同的字节数组:
>>> binascii.b2a_qp(command_stdout)
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
Run Code Online (Sandbox Code Playgroud)
有人知道如何将字节值转换回字符串吗?我的意思是,使用"电池"而不是手动操作.而且我希望它能用于Python 3.
我正在尝试使用scp
(安全复制)命令subprocess.Popen
.登录要求我发送密码:
from subprocess import Popen, PIPE
proc = Popen(['scp', "user@10.0.1.12:/foo/bar/somefile.txt", "."], stdin = PIPE)
proc.stdin.write(b'mypassword')
proc.stdin.flush()
Run Code Online (Sandbox Code Playgroud)
这会立即返回错误:
user@10.0.1.12's password:
Permission denied, please try again.
Run Code Online (Sandbox Code Playgroud)
我确定密码是正确的.我通过手动调用scp
shell 轻松验证它.那么为什么这不起作用呢?
请注意,有许多类似的问题,询问subprocess.Popen
并发送自动SSH或FTP登录的密码:
如何从python脚本在linux中设置用户密码?
使用子进程发送密码
这些问题的答案不起作用和/或不适用,因为我使用的是Python 3.