Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement for loop with "python -c" console command mode

Tags:

python

I have the below code which I want to run using python -c through a shell script:

import json,sys
obj=json.loads(open('/temp/209/209formatted_response.json','r').read())
revision=obj['component']['referencingComponents'][0]['revision']

for element in list(revision):
    if 'lastModifier' in element:
        del revision['lastModifier']

print(revision)

Using python -c , it runs fine without the for loop, but if I include the for loop in it, it throws and error:

Below works fine:

python -c "import json,sys; obj=json.loads(open('/temp/209/209formatted_response.json','r').read());revision=obj['component']['referencingComponents'][0]['revision']"

The below gives error:

$ /opt/app/anaconda3/envs/anaconda3/bin/python -c "import json,sys; obj=json.loads(open('/temp/209/209formatted_response.json','r').read());revision=obj['component']['referencingComponents'][0]['revision'];for element in list(revision):    if 'lastModifier' in element:        del revision['lastModifier']; print(revision)"
  File "<string>", line 1
    import json,sys; obj=json.loads(open('/temp/209/209formatted_response.json','r').read());revision=obj['component']['referencingComponents'][0]['revision'];for element in list(revision):    if 'lastModifier' in element:        del revision['lastModifier']; print(revision)
                                                                                                                                                                                      ^
SyntaxError: invalid syntax

I even tried using \n before each statement of the loop ; at the end of the line but no success

like image 710
djgcp Avatar asked Apr 12 '26 21:04

djgcp


1 Answers

One possible solution is to use newlines, but not bluntly adding them:

$ python3 -c "exec(\"n = 3\nfor i in range(n):\n  print(i)\")"
0
1
2

Add \n as you did, but also enclose the code by "exec(\"...\")"

Or you can insert real newlines:

$ python3 -c "n = 3
> for i in range(n):
>   print(i)"
0
1
2
like image 165
Kroshka Kartoshka Avatar answered Apr 15 '26 09:04

Kroshka Kartoshka