我需要一些帮助来弄清楚如何从 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 "print '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/