如何正确传递要使用 python -c 执行的文字字符串 python 代码

1 python string cmd literals

我需要一些帮助来弄清楚如何从 python -c 执行此 python 代码我在格式化 python 时遇到问题,以便它可以在 cmd 中为另一个应用程序执行我知道可能有其他方法可以做我正在做的事情,但我受到限制使用 cmd python -c 最终执行所以请记住这一点。

所以我有一些 python 代码,即

import os
import shutil

myPath =r"C:\dingdongz"
for root, dirs, files in os.walk(myPath):
    for file in files:
        os.remove(os.path(root, file))
    for dir in dirs:
        shutil.rmtree(os.path.join(root,dir))
Run Code Online (Sandbox Code Playgroud)

但我正在尝试使用以下方法执行它,python -c "p​​rint 'hotdogs'"

所以这就是我所拥有的,但没有用

cmdline = "\" import os, shutil \n for root, dirs, files in os.walk("+myPath+"):\n \t for file in files: \n \t \t os.remove(os.path.join(root, file)) \n \t for dir in dirs: \n \t\t shutil.rmtree(os.path.join(root, dir))" 

Windows CMD
python -c "+ cmdline +'"'
Run Code Online (Sandbox Code Playgroud)

Jak*_*yer 5

如果你真的需要做一个单行黑客(这完全不建议或宽恕),那么你可以这样做

python -c "import os; import shutil; for root, dirs, files in os.walk('+myPath+'): for file in files: os.remove(os.path.join(root, file)); for dir in dirs: shutil.rmtree(os.path.join(root, dir))"
Run Code Online (Sandbox Code Playgroud)

但是您真正应该做的是将其设为 Windows 路径内的脚本,然后您就可以执行了

python myfancyscript.py
Run Code Online (Sandbox Code Playgroud)

哪个看起来更好,对吗?