简体   繁体   中英

retrieving values from a finished running python script

i have a question related with python, anyway i have a script that has finished running, i give script1.py for example :

#script1.py
def test():
    x=1
    return x

val=test()

the question is how to retrieve script1.py after it has finished running?

i am doing something like this using script2.py but script1.py starts running again :

#sript2.py
import script1
val2=script1.val

do you know how to just retrieve the value from script1.py without restarting script1.py ?? any answer is appreciated, thx before

You can use below code.

from script1 import x

Example: script1:

c = 10

script2:

from script1 import c
print(c)

Let's look at what running script 1 does.

#script1.py 
def test():  # This defines a function, not an object
    x=1
    return x

val=test() # This assigns the object val={int}1

So what happens in script2 follows

#script2.py
import script1 # Evaluates the whole context of script1, which will "rerun" it
val2=script1.val # This value can only be "carried over" because it was reevaluated

Since the script is ran in two separate instances, the original value from script1 will not be saved, as it will be wiped out with the rest of the objects in script1.

eg If I rewrite script1 to the following, script2 will always crash:

#script1.py changed to break script2
def test():
    x=1
    return x

# Syntax for saying, only evaluate this value if I execute this, not on import
if __name__ == '__main__':
    val=test()

If you need the value to "persist" between contexts here you will need to to put that somewhere else. A simple way, or one of the first ways I learned how to, would be to pickle your data out to a file and read it back in script2.

https://www.geeksforgeeks.org/understanding-python-pickling-example/

#script1.py pickling
import pickle
pickled_output='s1.pkl'

def test():
    x=1
    return x

# Syntax for saying, only evaluate this value if I execute this, not on import
if __name__ == '__main__':
    val=test()
    with open(pickled_output,'wb') as pickled_file:
        pickle.dump(val, pickled_file)

#script2.py pickling
import pickle
import s1

with open(s1.pickled_output,'rb') as pickled_output:
    val2 = pickle.load(pickled_output)

This is nice because it is flexible to many types of objects and can make it clearer what you are doing in each stage. Plus it will raise an error if the file doesn't exist!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM