我目前正在复制以下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 调用的 PowerShell stdout 解码为 Python 字符串。
\n\n我的最终目标是以字符串列表的形式获取 Windows 上网络适配器的名称。我当前的函数如下所示,并且在使用英语的 Windows 10 上运行良好:
\n\ndef 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')
对他来说效果很好(因此它不是 …