A method of passing an instantiated object using the Python command line _python

Source: Internet
Author: User
Tags base64 eval string format

First, the preface

In the development process, we have a situation where we need to suprocess.call start another script (script B) by means of a method in the script, and, of course, we have to pass some arguments. Of these parameters, one needs to pass an instantiated object. We know that passing arguments by command line is based on character formatting, which means that script B can only receive parameters in string format, so how do you receive the instantiated object that the startup script passes over?

Let's talk today about the two stupid methods I use: Use and eval use pickle and base64 modules.

Method One: Use eval

In fact, the use of the code eval should not be good practice, but since you can temporarily solve the problem, why not take it to try? In fact, using this method does not pass the instantiated object on the command line, just putting the instantiated procedure in script B.

The following is a startup script:

Import subprocess
class Student (object):
 def __init__ (self):
  self.name = ' Chris '
  self.age =
 def __str__ (self): return
  ' \ n '. Join (' {}:{} '. Format (K_, v_) for K_, v_ in Self.__dict__.items ()
       if not k_. StartsWith ('_'))
def start_script ():
 # We delay the instantiation of the process
 commands = [' Python3 ', '/home/chris/projects/python /movie_wisdom/script.py ',
    ' Student () ']
 subprocess.call (commands)
if __name__ = ' __main__ ':
 Start_script ()

Here is the script that was started, the script B code:

From starter Import Student
def main ():
 student_obj = sys.argv[-1]
 # is instantiated to achieve the destination print for the "Delivery" Object
 ( Eval (student_obj))
main ()

Method two: Using Pickle and base64 modules

The idea used in this approach is described as follows:

1, startup script: pickle The module dumps method can serialize a Python object into a byte string;

2. Startup script: base64 the method of the module encodebytes can encode the binary byte string into a string;

3, the startup script: The base64 module decodebytes method is used to base64 convert the encoded string into a pickle module dumps after the byte string;

4, the startup script: The pickle module loads method converts the byte string in the previous step into an object instance.

It seems like the process is cumbersome, but it usually takes two lines of key code to solve the problem, but we're encapsulating it here in a function.

The code for the function is written as follows:

def pickle_dumps_to_str (obj):
 try: Return
  base64.encodebytes (pickle.dumps (obj)). Decode ()
 except Pickle. Picklingerror:
  pass
def pickle_loads_from_str (obj_str):
 try: Return
  pickle.loads ( Base64.decodebytes (Obj_str.encode ()))
 except Pickle. Unpicklingerror: Pass
  

Next, let's look at how to pass the instantiated object on the command line using the two functions above Student .

The startup code is rewritten as follows:

Def start_script ():
 student = student ()
 student.name = ' Mary '
 # at this time will be serialized student object instance (note and use ' eval ' difference) C4/>commands = [' Python3 ', '/home/chris/projects/python/movie_wisdom/script.py ',
    pickle_dumps_to_str (student) ]
 Subprocess.call (commands)

The script code that was started is rewritten as follows:

def main ():
 student_obj = sys.argv[-1]
 # Load Student object instance
 print (Pickle_loads_from_str (student_obj))

Summarize

The above is the entire content of this article, in fact, about this need to pass the instantiated object in the parameters of the method is not limited to this, but this should be considered a more special application scenario. If we have a better way, we also hope to have great God's advice. I hope this article will be helpful to friends who need it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.