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

标签 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))

但我尝试使用以下方法执行它, 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 +'"'

最佳答案

如果您确实需要进行单行破解(完全不建议或宽恕),那么您可以这样做

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))"

但是你真正应该做的是将其作为一个位于 Windows 路径内的脚本,然后你就可以执行

python myfancyscript.py

哪个看起来更好,对吧?

关于python - 如何正确传递要使用 python -c 执行的文字字符串 python 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5048375/

相关文章:

python - 如何为scrapy编写添加访问过的url的规则

c - 如何将字符数组中的字符串添加到 C 中的字符串

java - 在 Windows 控制台中从 Java 代码问题打印出 unicode

windows - 在批处理文件中使用时 TaskList 命令挂起

batch-file - 在任何计算机上查找 MSBuild 的路径

python - 如何在 python 脚本中获取 svn 两个修订版的完整上下文差异?

python - google.cloud 在哪个 python 库中?

c++ - 如何使用 Levenshtein 距离字符串度量

python - 在 hvplot 中自定义标记列表

android - 使用 toCharArray 转换字符串会产生不同的字符