Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am beginner in Python programing, I want to pass a complex object (Python dictionary or class object) as an argument to a python script using command line (cmd). I see that sys.argv gets only string parameters.

Here is an example of what I want:

class point(object):
     def __init__(self,x,y):
         self.__x=x
         self.__y=y
p=point(4,8)
import os
os.system('""xxxxxx.exe" "-s" "../create_scenario.py" "'+ p +'""')

The xxxxxx.exe is a program which accept to run a python script with the -s option. Thanks for all!!!

share|improve this question
5  
Sorry, we don't do urgent here. For time-critical answers, please hire a consultant. – Martijn Pieters Apr 18 at 11:58
os.system is really bad. – segfolt Apr 18 at 11:58
1  
Your only option is to save it to a file. On a side note: using __x is for name mangling which I'm pretty sure you don't need in the point class. You might have wanted a private variable _x if you have getter and setter functions/property but otherwise just leave it as self.x – jamylak Apr 18 at 11:59
segfolt >> What to use so if os.system is really bad ? – user2294884 Apr 18 at 12:02
See this post:stackoverflow.com/questions/3479728/… – segfolt Apr 18 at 12:13

2 Answers

You could use eval:

my_dict = eval(sys.argv[1])
print(my_dict)

Comand prompt:

$ my_script.py {1:2}
$ {1: 2}

But what you want to do is not recommended (see this post). You should avoid this and store your data in a file instead (using JSON for example).

share|improve this answer
Thank you. But how to use exec ? – user2294884 Apr 18 at 12:10
I did slight changes to my post. – segfolt Apr 18 at 12:25
1  
There are better alternatives than eval. Using JSON for example. – Martijn Pieters Apr 18 at 12:54

You could try serialize\deserialize to\from a string using a pickle module. Look for dumps and loads

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.