简体   繁体   English

使用 echo 写入文件的换行符在 shell 中有效,但在 Python 3 中为文字

[英]Newline character written to file with echo works in shell, but literal in Python 3

I'm on a Ubuntu 20.04 system, and I'm using Python 3.8 to write a script that does multiple things using configurable lines of bash, but one of them is that it creates desktop shortcuts.我在Ubuntu 20.04系统上,我正在使用Python 3.8编写一个脚本,该脚本使用可配置的 bash 行执行多项操作,但其中之一是它创建了桌面快捷方式。

This single-line command creates a desktop shortcut, and works flawlessly when I execute it directly in my terminal :这个单行命令创建了一个桌面快捷方式,当我直接在终端中执行它时可以完美运行

echo "[Desktop Entry]"$'\n'"Type=Application"$'\n'"Name[en_US]=Documents"$'\n'"Exec=pcmanfm ~/Documents"$'\n'"Icon=system-file-manager" > ~/Desktop/1;

However, when I execute it in Python, like so:但是,当我在 Python 中执行它时,如下所示:

foobar.py

rl = """echo "[Desktop Entry]"$'\n'"Type=Application"$'\n'"Name[en_US]=Documents"$'\n'"Exec=pcmanfm ~/Documents"$'\n'"Icon=system-file-manager" > ~/Desktop/1;"""
subprocess.run(rl, shell=True)

...instead of creating a desktop shortcut with the proper name, icon, and action, it creates an empty file that contains the following text : ...它不是创建具有正确名称、图标和操作的桌面快捷方式,而是创建一个包含以下文本的空文件

0.txt : 0.txt

[Desktop Entry]$\nType=Application$\nName[en_US]=Sign Out$\nExec=/home/agent/QaSC/login/login.bin$\nIcon=system-switch-user

Is there any particular reason why Python would be handling the newline characters differently than the bash shell does, and if so, how can I resolve this problem?是否有任何特殊原因导致 Python 处理换行符的方式与 bash shell 不同,如果是,我该如何解决这个问题?

$'...' is a bash extension, but the default shell used when shell=True is specified is sh . $'...'是一个bash扩展,但指定shell=True时使用的默认 shell 是sh Use the executable option to specify an alternate shell.使用executable选项指定备用外壳。

subprocess.run(rl, shell=True, executable='/bin/bash')

Since the argument to echo has quotes, it could contain literal newlines at the command line, and therefore also in the Python process.由于echo的参数有引号,它可以在命令行中包含文字换行符,因此也在 Python 进程中。 I see no reason to use the Bash extension $'\n' syntax.我认为没有理由使用 Bash 扩展$'\n'语法。

$ echo "foo
> bar"
foo
bar
$ python
Python 3.8.10 (default, Mar 15 2022, 12:22:08) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> subprocess.run('echo "foo\nbar"', shell=True)
foo
bar
CompletedProcess(args='echo "foo\nbar"', returncode=0)
>>> 

(It's also unclear why the Python code doesn't just write a file in the normal way, but I assume the command in the OP is essentially a placeholder.) (也不清楚为什么 Python 代码不只是以正常方式编写文件,但我认为 OP 中的命令本质上是一个占位符。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM