1

I need some help figuring out how to execute this python code from python -c I am have trouble formatting python so that it will execute for another app in cmd I understand there maybe other ways to do what I am doing but I am limited by the final execution using cmd python -c so please keep this in mind.

So I have some python code ie,

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

But I am trying to excute it using the following method, python -c "print 'hotdogs'"

So this what i have but no worky

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 +'"'

3 Answers 3

6

If you really really need to do a one line hack (this is totally not suggested or condoned) then you can do this

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

But what you should really do is make this a script that is inside your windows path, then you can do

python myfancyscript.py

Which seems a lot nicer right?

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for replying but like I said above I'm limited by the final delivery of code. The python is being called by a server that does not have access to any python script I create, ie"myfancyscript.py" I try to run you solution above but I am still getting error tree(os.path.join(root, dir)) ^ SyntaxError: invalid syntax
0

Powershell guidelines for using python -c

  • enclose the whole code section in " - so that you evaluate PowerShell special characters within (for newlines and tabs)
  • use ' for quotes within the code section
  • use `n as line separators
  • use `t as tab character essential for python indentation

Example: minify json oneliner

  • that takes foo.json as an input and prints it minified version to the console
python -c "import json`nimport sys`nwith open(sys.argv[1], 'r') as f:`n`tprint(json.dumps(json.load(f), separators=(',',':')))" foo.json

Comments

0

For CMD, enclose the whole code section within double quotes ". Else it will simply not work (no output).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.