如何在Windows下用Python执行Linux命令?解决换行符兼容问题
在Windows通过Python调用WSL执行Linux命令时的换行符问题及解决方法
背景
我需要研究如何用Python执行Linux命令。由于使用Windows系统,需先执行wsl切换到微软商店下载的Ubuntu发行版。我不是Python程序员,目前是Java实习生,该Python脚本最终会部署在Linux机器上,但当前只能用这种方式测试。
问题
尝试逐个执行命令列表中的命令时,每个命令末尾都会出现回车符(\r)。原因是Windows DOS使用\r\n作为行结束符,而Linux仅使用\n。
原Python脚本:
import subprocess commands=["ls -al ~","pwd"] # Initialize the WSL process process = subprocess.Popen("wsl", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) # Execute each command in WSL for command in commands: process.stdin.write((command)+"\n") # Close the stdin and wait for the process to complete process.stdin.close() process.wait() # Read and print the response from WSL output = process.stdout.read() print("WSL:", output)
错误输出:
WSL: ls: cannot access '~'$'\r': No such file or directory -bash: line 2: $'pwd\r': command not found
解决方案1
write方法会自动把\n转换为\r\n,可通过指定newline=''避免这种转换,代码如下:
import subprocess commands=["ls -al ~","pwd"] # Initialize the WSL process process = subprocess.Popen("wsl", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) # Execute each command in WSL with open(process.stdin.fileno(), mode='w', newline='') as f: for command in commands: f.write((command)+'\n') # Read and print the response from WSL output = process.stdout.read() print("WSL:", output)
提问者自行解决的方案2
通过subprocess.run单独执行每个命令,配合shlex.split解析命令参数,避免行结束符问题,代码如下:
import subprocess import shlex # Define a list of commands commands = ["ls -al ~", "pwd", "pwd"] # Initialize the WSL process and execute each command for command in commands: command_list = shlex.split(command) # 在Linux环境运行时移除['wsl'] # 默认假设shell是bash,若不是可替换'wsl'为对应shell(如'bash') result = subprocess.run(['wsl'] + command_list, stdout=subprocess.PIPE, text=True) print("WSL:", result.stdout)
内容的提问来源于stack exchange,提问作者Hussain Ahmed Siddiqui
相关产品推荐
相关产品推荐

