Hi I am writing python for the first time:
I have a existing getprop.py script that loads the property file and prints the value of a given property:
import sys
import util
if len(sys.argv) < 3:
print "Error! Usage is: getprop.py [propfile] [propname]"
sys.exit(1)
props = util.loadprops(sys.argv[1])
if sys.argv[2] in props:
print props(sys.argv[2]);
Now I need to get the value of a property in another py script, so I modified the above script such that I do not disturb its functionality and I can use it in another script:
import sys
import util
def getpropvalue(propfile, propname):
props = util.loadprops(propfile)
if propname in props:
return props[propname]
if len(sys.argv) < 3:
print "Error! Usage is: getprop.py [propfile] [propname]"
sys.exit(1)
else:
print getpropvalue(sys.argv[1], sys.argv[2]);
and then in other script I import getprop and call the method like getprop.getpropvalue(FILE_NAME, PROP_NAME)and it prints the value of the property on the screen.
why does it prints the value? Is there any better way to solve this problem?
There is a way to run the script only if it was called directly. Add those lines to the end of your getprop
code:
if __name__ == "__main__":
main()
This way the main
function is only going to be called if you run the script directly (not importing). Is that what you're looking for?
Some explanation: every running script has a __name__
variable that will be set to "__main__"
if you run the script from an IDE or console like python script.py
Change your getprop.py to this:
import sys
import util
def getpropvalue(propfile, propname):
props = util.loadprops(propfile)
if propname in props:
return props[propname]
if __name__ == '__main__':
if len(sys.argv) < 3:
print "Error! Usage is: getprop.py [propfile] [propname]"
sys.exit(1)
else:
print getpropvalue(sys.argv[1], sys.argv[2]);
This will prevent the code from being executed when it is imported.
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.