Name 'main' not defined - python

I was trying to make tetris game using reinforcement learning. I get this name undefined error.Thanks in advance for the solution
class TetrisApp
...........
..........
other code
..........
..........
def main(argv):
cp = ''
try:
opts, args = getopt.getopt(argv,"hc:c:",["computer_player="])
except getopt.GetoptError:
print 'tetris.py -c[--computer_player] <True>|<False>'
sys.exit(2)
if len(opts) == 0 :
play(True)
for opt, arg in opts:
if opt == '-h':
print 'tetris.py -c <True>|<False>'
sys.exit()
elif opt in ("-c", "--computer_player"):
cp = arg
if cp == 'True':
play(True)
else:
play(False)
if __name__ == "__main__":
main(sys.argv[1:])

for calling Class methods Outside the class Use Class Object.
t=TetrisApp()
t.main(sys.argv[1:])
and use self in method def main(self,argv):

Related

Rerun python script after 10 seconds

I am trying to rerun my python script every 10 seconds. I have tried various things with the time.sleep function but nothing seems to be working. I have tried different variants of time.sleep:
def job()
# script
if __name__ == '__main__':
while True:
job()
time.sleep(10)
but not finding the correct place/way to implement it. I don't want to rerun a function, but the full code.
This is the script I am trying to rerun:
import...
def main():
# parse the command line arguments
args = ConfigArgumentParser(description=__doc__).parse_args()
if _debug: _log.debug("initialization")
if _debug: _log.debug(" - args: %r", args)
# make a device object
this_device = LocalDeviceObject(
objectName=args.ini.objectname,
objectIdentifier=('device', int(args.ini.objectidentifier)),
maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted),
segmentationSupported=args.ini.segmentationsupported,
vendorIdentifier=int(args.ini.vendoridentifier),
)
# make a sample application
this_application = BIPSimpleApplication(this_device, args.ini.address)
# make some random input objects
for i in range(1, RANDOM_OBJECT_COUNT + 1):
ravo = RandomAnalogValueObject(
objectIdentifier=('analogValue', i),
objectName='Temp%d' % (i,),
)
this_application.add_object(ravo)
# make sure they are all there
_log.debug(" - object list: %r", this_device.objectList)
_log.debug("running")
run()
_log.debug("fini")
if __name__ == "__main__":
main()
If you need the whole thing to run (even bootstrap code), you can use a shell script to do it.
This won't refresh environment variables though.
#!/usr/bin/env bash
while true; do
sleep 10
python script.py
done
If you need to refresh environment variables (you seem to need it because of RANDOM_OBJECTS), add eval "$(exec /usr/bin/env -i "${SHELL}" -l -c "export")" to the mix. Source: https://unix.stackexchange.com/a/581684
Try this:
if __name__ == "__main__":
time.sleep(10)
main()
What you can do is just restart your whole script after 10s.
Applied to your code it would look like this:
import os
import time
import json
import sys
from bacpypes.debugging import bacpypes_debugging, ModuleLogger
from bacpypes.consolelogging import ConfigArgumentParser
from bacpypes.core import run
from bacpypes.primitivedata import Real
from bacpypes.object import AnalogValueObject, Property, register_object_type
from bacpypes.errors import ExecutionError
from bacpypes.app import BIPSimpleApplication
from bacpypes.local.device import LocalDeviceObject
# Read Json
with open('ObjectList.json') as json_file:
data = json.load(json_file)
def get_present_value(no):
for a in data['AnalogValues']:
if a['ObjectIdentifier'] == int(no):
return a['PresentValue']
return None
ai_1 = (get_present_value(1))
print(ai_1)
# some debugging
_debug = 0
_log = ModuleLogger(globals())
# settings
RANDOM_OBJECT_COUNT = int(os.getenv('RANDOM_OBJECT_COUNT', 1))
#
# RandomValueProperty
#
class RandomValueProperty(Property):
def __init__(self, identifier):
if _debug: RandomValueProperty._debug("__init__ %r", identifier)
Property.__init__(self, identifier, Real, default=0.0, optional=True, mutable=False)
def ReadProperty(self, obj, arrayIndex=None):
if _debug: RandomValueProperty._debug("ReadProperty %r arrayIndex=%r", obj, arrayIndex)
# access an array
if arrayIndex is not None:
raise ExecutionError(errorClass='property', errorCode='propertyIsNotAnArray')
# return a random value
value = ai_1
if _debug: RandomValueProperty._debug(" - value: %r", value)
return value
def WriteProperty(self, obj, value, arrayIndex=None, priority=None, direct=False):
if _debug: RandomValueProperty._debug("WriteProperty %r %r arrayIndex=%r priority=%r direct=%r", obj, value,
arrayIndex, priority, direct)
raise ExecutionError(errorClass='property', errorCode='writeAccessDenied')
bacpypes_debugging(RandomValueProperty)
#
# Random Value Object Type
#
class RandomAnalogValueObject(AnalogValueObject):
properties = [
RandomValueProperty('presentValue'),
]
def __init__(self, **kwargs):
if _debug: RandomAnalogValueObject._debug("__init__ %r", kwargs)
AnalogValueObject.__init__(self, **kwargs)
bacpypes_debugging(RandomAnalogValueObject)
register_object_type(RandomAnalogValueObject)
#
# __main__
#
def main():
# parse the command line arguments
args = ConfigArgumentParser(description=__doc__).parse_args()
if _debug: _log.debug("initialization")
if _debug: _log.debug(" - args: %r", args)
# make a device object
this_device = LocalDeviceObject(
objectName=args.ini.objectname,
objectIdentifier=('device', int(args.ini.objectidentifier)),
maxApduLengthAccepted=int(args.ini.maxapdulengthaccepted),
segmentationSupported=args.ini.segmentationsupported,
vendorIdentifier=int(args.ini.vendoridentifier),
)
# make a sample application
this_application = BIPSimpleApplication(this_device, args.ini.address)
# make some random input objects
for i in range(1, RANDOM_OBJECT_COUNT + 1):
ravo = RandomAnalogValueObject(
objectIdentifier=('analogValue', i),
objectName='Temp%d' % (i,),
)
this_application.add_object(ravo)
# make sure they are all there
_log.debug(" - object list: %r", this_device.objectList)
_log.debug("running")
run()
_log.debug("fini")
if __name__ == "__main__":
main()
time.sleep(10)
os.execl(sys.executable, sys.executable, * sys.argv) # Your script restarts after 10s with this

How to parse arguments to a function in Python?

I've been trying to understand tutorials on how to parse arguments in Python using argparse. Is this how I would pass a command line input so I can run a function?
import argparse
parser = argparse.ArgumentParser(description='A test')
parser.add_argument("--a", default=1, help="Test variable")
args = parser.parse_args()
def foo():
command_line_argument = args.a
bar = 2*args.a
print(bar)
return
if "__name__" == "__main__"
try:
while True:
foo()
except KeyboardInterrupt:
print('User has exited the program')
That while True looks odd to me -- are you asking the reader to keep submitting inputs until they CTRL+C ? Because if so, argparse is the wrong thing to use: see Getting user input
If you intend a single argument then I'd move the parser stuff inside main, which is what gets executed when the script is run as a program as opposed to being imported.
Also, I'd pass a parameter to foo rather than the args block.
Lastly, I guess you're expecting to receive a number so you need type=int or similar.
import argparse
def foo(a):
bar = 2*a
print(bar)
return
if __name__ == "__main__":
try:
# set it up
parser = argparse.ArgumentParser(description='A test')
parser.add_argument("--a", type=int, default=1, help="Test variable")
# get it
args = parser.parse_args()
a = args.a
# use it
foo(a)
except KeyboardInterrupt:
print('User has exited the program')
So:
$ python foo.py --a 1
2
below is in working state
import argparse
parser = argparse.ArgumentParser(description='A test')
parser.add_argument("--a", default=1, help="Test variable", type=int)
args = parser.parse_args()
def foo():
command_line_argument = args.a
bar = 2*args.a
print(bar)
return
if __name__ == "__main__":
try:
while True:
foo()
except KeyboardInterrupt:
print('User has exited the program')
if you run python your-filename.py --a=2 it will print 4 until you stop the execution.

in python, how to make main args global

I want to access the args values in a class function in python.
For example, I wrote a sample test program below.
#!/usr/bin/env python
import argparse
class Weather(object):
def __init__(self):
self.value = 0.0
def run(self):
print('in weather.run')
if (args.sunny == True):
print('It\'s Sunny')
else:
print('It\'s Not Sunny')
def main():
argparser = argparse.ArgumentParser(
description=__doc__)
argparser.add_argument(
'--sunny', action='store_true', dest='sunny', help='set if you want sunny weather')
args = argparser.parse_args()
print('args.sunny = ', args.sunny)
weather = Weather()
weather.run()
if __name__ == '__main__':
main()
When I run it(./test.py), I get errors below.
('args.sunny = ', False)
in weather.run
Traceback (most recent call last):
File "./test.py", line 30, in <module>
main()
File "./test.py", line 27, in main
weather.run()
File "./test.py", line 10, in run
if (args.sunny == True):
NameError: global name 'args' is not defined
I tried putting 'global args' in the Weather.run function but got the same error. What is the correct method?
You can set it global by:
global args
args = argparser.parse_args()
or just pass sunny as argument to weather:
def run(self, sunny):
.....
weather.run(self, args.sunny)
Why don't you add whatever is in main() into the if statement?
#!/usr/bin/env python
import argparse
class Weather(object):
def __init__(self):
self.value = 0.0
def run(self):
print('in weather.run')
if (args.sunny == True):
print('It\'s Sunny')
else:
print('It\'s Not Sunny')
if __name__ == '__main__':
argparser = argparse.ArgumentParser(
description=__doc__)
argparser.add_argument(
'--sunny', action='store_true', dest='sunny', help='set if you want sunny weather')
args = argparser.parse_args()
print('args.sunny = ', args.sunny)
weather = Weather()
weather.run()
The two answers provided didn't match my app's design, this worked for me though:
class Weather(object):
def run(self):
if (args.sunny == True):
print('It\'s Sunny')
else:
print('It\'s Not Sunny')
def main():
global args
args = argparser.parse_args()

Getopt multiple argument syntaxes

So I'm working on an assignment in a python class that I'm taking, but have gotten stuck with something I can't really find any further information about (neither on SO, Google or in the courseware).
I need help with how to handle arguments with multiple types of syntaxes - like [arg] and < arg >, which is something I've been unable to find any further information about.
Here is an example use-case that SHOULD work.
>>> ./marvin-cli.py --output=<filename.txt> ping <http://google.com>
>>> Syntax error near unexpected token 'newline'
The below code works fine for any use-case where I haven't defined any further output than writing to the console:
# Switch through all options
try:
opts, args = getopt.getopt(sys.argv[1:], "hsv", ["help","version","silent", "get=", "ping=", "verbose", "input=", "json"])
for opt, arg in opts:
if opt in ("-h", "--help"):
printUsage(EXIT_SUCCESS)
elif opt in ("-s", "--silent"):
VERBOSE = False
elif opt in ("--verbose"):
VERBOSE = True
elif opt in ("--ping"):
ping(arg)
elif opt in ("--input"):
print("Printing to: ", arg)
else:
assert False, "Unhandled option"
except Exception as err:
print("Error " ,err)
print(MSG_USAGE)
# Prints the callstack, good for debugging, comment out for production
#traceback.print_exception(Exception, err, None)
sys.exit(EXIT_USAGE)
#print(sys.argv[1])
Example usage:
>>> ./marvin-cli.py ping http://google.com
>>> Latency 100ms
And this is a snippet showing how the ping works:
def ping(URL):
#Getting necessary imports
import requests
import time
#Setting up variables
start = time.time()
req = requests.head(URL)
end = time.time()
#printing result
if VERBOSE == False:
print("I'm pinging: ", URL)
print("Received HTTP response (status code): ", req.status_code)
print("Latency: {}ms".format(round((end - start) * 1000, 2)))
[] and <> are commonly used to visually indicate option requirement. Typically [xxxx] means the option or argument is optional and <xxxx> required.
The sample code you provide handles option flags, but not the required arguments. Code below should get you started in the right direction.
try:
opts, args = getopt.getopt(sys.argv[1:], "hsv", ["help", "version", "silent", "verbose", "output=", "json"])
for opt, arg in opts:
if opt in ("-h", "--help"):
printUsage(EXIT_SUCCESS)
elif opt in ("-s", "--silent"):
VERBOSE = False
elif opt in ("--verbose"):
VERBOSE = True
elif opt in ("--output"):
OUTPUTTO = arg
print("Printing to: ", arg)
else:
assert False, "Unhandled option"
assert len(args) > 0, "Invalid command usage"
# is there a "<command>" function defined?
assert args[0] in globals(), "Invalid command {}".format(args[0])
# pop first argument as the function to call
command = args.pop(0)
# pass args list to function
globals()[command](args)
def ping(args):
#Getting necessary imports
import requests
import time
# validate arguments
assert len(args) != 1, "Invalid argument to ping"
URL = args[0]
#Setting up variables
start = time.time()
req = requests.head(URL)
end = time.time()
#printing result
if VERBOSE == False:
print("I'm pinging: ", URL)
print("Received HTTP response (status code): ", req.status_code)
print("Latency: {}ms".format(round((end - start) * 1000, 2)))

Python functions and calling args

I'm creating my first python tool, if you want to call it that. (I work in IT Security, btw)
It was going well until I tried to call a function from the main function. I'm sure it's something simple that I'm missing :(. Could someone point me in the right direction? Then feel free to point and laugh.
#!/usr/bin/python
import sys, getopt, socket
def usage():
print "-h --help: help\n"
print "-f --file: File to read bruteforce domain list from.\n"
print "-p --proxy: Proxy address and port. e.g http://192.168.1.64:8080\n"
print "-d --domain: Domain to bruteforce.\n"
print "-e: Turn debug on.\n"
sys.exit()
def main(argv):
file = None
proxy = None
domain = None
try:
opts, argv =getopt.getopt(argv, "h:f:p:d:e",["help", "file=", "proxy=", "domain="])
except getopt.GetoptError as err:
print str(err)
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-f", "--file"):
file = arg
elif opt in ("-p", "--proxy"):
proxy = arg
elif opt in ("-d", "--domain"):
domain = arg
elif opt in '-e':
global _debug
_debug = 1
else:
assert Flase, "Unhandled option"
print fread.flist
def fread(file, *args):
flist = open(file).readlines()
return
if __name__ == "__main__":
main(sys.argv[1:])
The issue is with your statement print fread.flist. You can't access variables assigned inside functions this way. Instead, change your fread() function to the following:
def fread(file, *args):
flist = open(file).readlines()
return flist
and change the statement above to
print fread(file)
where file is the file you want to access.

Categories