相关疑难解决方法(0)

在Python中重现Unix cat命令

我目前正在复制以下Unix命令:

cat command.info fort.13 > command.fort.13
Run Code Online (Sandbox Code Playgroud)

在Python中使用以下内容:

with open('command.fort.13', 'w') as outFile:
  with open('fort.13', 'r') as fort13, open('command.info', 'r') as com:
    for line in com.read().split('\n'):
      if line.strip() != '':
        print >>outFile, line
    for line in fort13.read().split('\n'):
      if line.strip() != '':
        print >>outFile, line
Run Code Online (Sandbox Code Playgroud)

这是有效的,但必须有一个更好的方法.有什么建议?

编辑(2016):

四年后,这个问题又开始受到关注.我在这里用更长的Jupyter笔记本写了一些想法.

问题的关键在于我的问题与(我意想不到的)行为有关readlines.我可以更好地回答我的目标,这个问题可以更好地回答read().splitlines().

python cat

9
推荐指数
3
解决办法
3万
查看次数

将可能包含非 ASCII Unicode 字符的 PowerShell 输出解码为 Python 字符串

我需要将从 Python 调用的 PowerShell stdout 解码为 Python 字符串。

\n\n

我的最终目标是以字符串列表的形式获取 Windows 上网络适配器的名称。我当前的函数如下所示,并且在使用英语的 Windows 10 上运行良好:

\n\n
def get_interfaces():\n    ps = subprocess.Popen(['powershell', 'Get-NetAdapter', '|', 'select Name', '|', 'fl'], stdout = subprocess.PIPE)\n    stdout, stdin = ps.communicate(timeout = 10)\n    interfaces = []\n    for i in stdout.split(b'\\r\\n'):\n        if not i.strip():\n            continue\n        if i.find(b':')<0:\n            continue\n        name, value = [ j.strip() for j in i.split(b':') ]\n        if name == b'Name':\n            interfaces.append(value.decode('ascii')) # This fails for other users\n    return interfaces\n
Run Code Online (Sandbox Code Playgroud)\n\n

其他用户使用不同的语言,因此value.decode('ascii')其中一些用户会失败。例如,一位用户报告说更改为decode('ISO 8859-2')对他来说效果很好(因此它不是 …

windows unicode powershell subprocess python-3.x

6
推荐指数
1
解决办法
4625
查看次数

标签 统计

cat ×1

powershell ×1

python ×1

python-3.x ×1

subprocess ×1

unicode ×1

windows ×1