我正在使用此代码从外部程序获取标准输出:
>>> 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.
我需要*.bat
在Windows 上使用脚本加入两个二进制文件.
我怎样才能做到这一点?
当我尝试在Windows控制台中打印Unicode字符串时,出现UnicodeEncodeError: 'charmap' codec can't encode character ....
错误.我认为这是因为Windows控制台不接受仅Unicode字符.最好的方法是什么??
在这种情况下,有什么方法可以让Python自动打印而不是失败?
编辑: 我正在使用Python 2.5.
注意: @ LasseV.Karlsen回答带有复选标记有点过时(从2008年开始).请谨慎使用下面的解决方案/答案/建议!!
截至今天(2016年1月6日),@ JFSebastian答案更为相关.
我正在尝试使用Process.Start
重定向的I/O来调用PowerShell.exe
字符串,并以UTF-8的形式返回输出.但我似乎无法做到这一点.
我尝试过的:
-Command
参数运行Console.OutputEncoding
在这两个我的控制台应用程序,并在PowerShell脚本$OutputEncoding
在PowerShell中设置Process.StartInfo.StandardOutputEncoding
Encoding.Unicode
而不是做到这一切Encoding.UTF8
在每种情况下,当我检查我给出的字节时,我会得到与原始字符串不同的值.我真的很想解释为什么这不起作用.
这是我的代码:
static void Main(string[] args)
{
DumpBytes("Héllo");
ExecuteCommand("PowerShell.exe", "-Command \"$OutputEncoding = [System.Text.Encoding]::UTF8 ; Write-Output 'Héllo';\"",
Environment.CurrentDirectory, DumpBytes, DumpBytes);
Console.ReadLine();
}
static void DumpBytes(string text)
{
Console.Write(text + " " + string.Join(",", Encoding.UTF8.GetBytes(text).Select(b => b.ToString("X"))));
Console.WriteLine();
}
static int ExecuteCommand(string executable, string arguments, string workingDirectory, Action<string> output, Action<string> error)
{
try
{
using …
Run Code Online (Sandbox Code Playgroud) 如何\n
在Windows上打印到stdout?此代码适用于Python 2,但不适用于Python 3:
# set sys.stdout to binary mode on Windows
import sys, os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
# the length of testfile created with
# python test_py3k_lf_print.py > testfile
# below should be exactly 4 symbols (23 0A 23 0A)
print("#\n#")
Run Code Online (Sandbox Code Playgroud) 在没有人告诉我之前,我完全意识到我想要做的事情是荒谬的,但是我有我的理由。
我有一台可以在其中编写脚本(bash或python)的服务器。该脚本需要接受来自STDIN的二进制数据并将其保存到文件中。确切地说,二进制数据是WAV文件。
我正在使用的是名为Workflow的iOS应用。该应用程序将允许我录制音频文件,然后将其作为STDIN输入发送到将通过SSH运行的脚本。因此,我的脚本需要采用该STDIN输入并将其保存到文件中。
有什么想法/想法吗?我完全不知道该从哪里开始。
python ×3
python-3.x ×2
windows ×2
bash ×1
binary ×1
command-line ×1
encoding ×1
powershell ×1
scripting ×1
ssh ×1
stdin ×1
stdout ×1
string ×1
unicode ×1
utf-8 ×1