python不会打印出“;性格

python不会打印出“;性格,python,python-3.x,Python,Python 3.x,我有个奇怪的问题。我需要从stat命令打印输出字符串 我已经编写了获取一些信息的代码 import glob import os for file in glob.glob('system1/**', recursive=True): os.system("stat -c \"set_metadata(/%n \"uid\", %u, \"gid\", %g, \"mode\", 0%a, \"c

我有个奇怪的问题。我需要从
stat
命令打印输出字符串

我已经编写了获取一些信息的代码

import glob
import os

for file in glob.glob('system1/**', recursive=True):
    os.system("stat -c \"set_metadata(/%n \"uid\", %u, \"gid\", %g, \"mode\", 0%a, \"capabilities\", 0x0, \"selabel\", \"later\");\" "f"{file}")
预期产出:

set_metadata("/system1/xbin/jack_transport" "uid", 0, "gid", 2000, "mode", 0755, "capabilities", 0x0, "selabel", "later");
但我的输出如下所示:

set_metadata(/system1/xbin/jack_transport uid, 0, gid, 2000, mode, 0755, capabilities, 0x0, selabel, later);
它没有在那里打印一个
。为什么呢?我尝试过用替换“with”,这很有效,但这不是我所需要的。

os.system()。您可以从Python和shell中反斜杠转义引号,但它很快就会变得复杂,因为您也必须从Python中反斜杠转义用于shell的反斜杠转义

适当的引用看起来像

glob.glob('system1/**',recursive=True)中的文件的
:
系统(f““stat-c”set_元数据(/%n”uid“,%u,“gid”,%g,“mode”,0%a,“capabilities”,0x0,“selabel”,“later”);“{file}”“)
在这里,我们使用Python的三重引号将文本单引号和双引号传递给shell

当然,更好的解决方案是使用
子流程
,它允许您完全绕过shell

glob.glob('system1/**',recursive=True)中的文件的
:
subprocess.run(['stat','-c',],
'设置元数据(/%n“uid”、%u,“gid”、%g,“mode”,0%a,“capabilities”,0x0,“selabel”,“later”),
文件],检查=True)
但是,如果所有实际的业务逻辑都在shell脚本中,那么为什么要使用Python呢

#/bin/bash
stat-c'set_元数据(/%n“uid”,%u,“gid”,%g,“mode”,0%a,“capabilities”,0x0,“selabel”,“later”)\n'系统1/**

(如果glob返回大量匹配项,您可能需要使用
xargs
将其分解。)

您是否也要逃避
“f”
?@ewong否。也感谢您的回答。您可以编辑您的帖子以显示您期望的输出吗?@DrBwts我已经在帖子的开头添加了它。好的,我把它移下来