Argparser interactive - argparse

My question is pretty straight,
Is argaparse has an option to prompt missed arguments just via input?
script.py:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('mode', metavar='', help='Set count of likes', default=49)
parser.add_argument('-n', '--number', metavar='', help='Set count of likes', default=49, required=True)
parser.add_argument('-f', '--frequency', metavar='', help='Set chance to like/dislike', default=70)
# Running it via bash:
$ python script.py
# argparse automaticaly checking that missed argument "--number" and asking it via input built-in
>>> (argparse) Missed required argument "number", please specify it now, number:

Related

how to run an execution from a launchplan with flytesdk

I'm trying to use the flytesdk to run an execution from a launch plan.
I was given an example of
lp = SdkLaunchPlan.fetch('project', 'domain', 'name', 'version')
ex = lp.execute('project', 'domain' inputs={'a': 1, 'b': 'hello'}, <name='optional idempotency string'>)
but it looks like SdkLaunchPlan.execute() is not implemented but SdkLaunchPlan.execute_with_literals() is.
I was able to execute it with this code:
#I omitted the version parameter because the launch plan is active
lp = flytekit.common.launch_plan.SdkLaunchPlan.fetch(project="prj", domain="development", name="train.single.test_launch_plan")
literals = flytekit.clis.helpers.construct_literal_map_from_parameter_map(lp.default_inputs, {"depth": "False"})
lp.execute_with_literals("prj", "development", literal_inputs=literals)
is this the correct way of doing this or is there a better one?
Which version of flytekit are you on? Both should work. I think execute is a bit easier to use when you have an ipython terminal running. I was able to launch an execution on my cluster with the following commands.
(examples3) alice:~ [docker-desktop] $ ipython
Python 3.7.5 (default, Nov 1 2019, 02:16:32)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.7.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: from flytekit.clis.flyte_cli.main import _detect_default_config_file
Using default config file at /Users/alice/.flyte/config
In [2]: from flytekit.common.launch_plan import SdkLaunchPlan
In [3]: lp = SdkLaunchPlan.fetch("flyteexamples", "development", "app.workflows.work.WorkflowWithIO", "8f49b8d8c04251865a7a8aba1b423293efc51374")
In [4]: lp.execute('flyteexamples', 'development', inputs={'a': 42, 'b': 'hello world'})
The code for execute_with_literals is here:
https://github.com/lyft/flytekit/blob/5a0a8da9251bd13bd67b71e0b05b6e59ecb970f9/flytekit/common/launch_plan.py#L186
And the code for execute is here:
https://github.com/lyft/flytekit/blob/5a0a8da9251bd13bd67b71e0b05b6e59ecb970f9/flytekit/common/mixins/executable.py#L8
The difference between the two is that one is meant to work with raw Python literals and the other is meant to work with Flyte literal types.
My bad, it looks like my editor's (VSCode) autocomplete did not recognize the .execute() method...I tried it anyways and it's working as advertised

stderr changes behavior of python's Popen when closing the script

I was using this script on python2 to launch an application and then immediately exit the python script without waiting for the child process to end. This was my code:
kwargs = {}
if platform.system() == 'Windows':
# from msdn [1]
CREATE_NEW_PROCESS_GROUP = 0x00000200 # note: could get it from subprocess
DETACHED_PROCESS = 0x00000008 # 0x8 | 0x200 == 0x208
kwargs.update(creationflags=DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)
kwargs.update(stderr=subprocess.PIPE)
elif sys.version_info < (3, 2): # assume posix
kwargs.update(preexec_fn=os.setsid)
else: # Python 3.2+ and Unix
kwargs.update(start_new_session=True)
subprocess.Popen([APP], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,**kwargs)
It works OK on python 2.7, but it doesn't start the expected 'APP' on python 3.7 without changes.
In order to make it work in python3, I found two independent workarounds:
Change stderr to this: stderr=subprocess.DEVNULL
or
Add a time.sleep(0.1) call after the Popen (before closing the script).
I assume this is not actually related to python, but to some event that needs to happen after the process gets opened before the python script can safely exit?
Any hints? I'd really like to know why it happens. Right now I simply added the sleep call.
Thank you

error in use of tf.app.flags

I used tf.app.flags in my tensorflow program like this:
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('model_dir', './models','Save checkpoint')
.
.
.
if __name__ == "__main__":
# main()
tf.app.run()
But when run my code two time it makes this error:
ArgumentError: argument --model_dir: conflicting option string: --model_dir
I think tensorflow create a argument for --model_dir and when it run again it try to create again a argument for --model_dir, but conflicted by existence --model_dir.
are there any way two solve this problem or I used python parameters against tf.app.falgs?
My guess is that you are working in an environment like a Jupyter/iPython notebook.
The reason you are having this issue is that the flags data seems to be maintained within the Python session. tf.app.flags.FLAGS.__getattr__('model_dir') is equal to ./models even if you reset your variable FLAGS.
If you are using a notebook, I suggest you put your flag definitions in a separate cell. The only way that I found to reset tf.app.flags.FLAGS is to restart the kernel/session.
You can try like this:
#define flags
tf.flags.DEFINE_integer("age", 17, "age of user(default:20)")
tf.flags.DEFINE_boolean("drink_allow", False, "if can drink or not(default:False)")
tf.flags.DEFINE_float("weight", 55.55, "weight of user(default:55.55kg)")
FLAGS = tf.flags.FLAGS #init flags
FLAGS._parse_flags() # parse flags
for attr,value in FLAGS.__flags.items():
print("attr:%s\tvalue:%s" % (attr,str(value)))

API doesn't work. (IP-API)

I wanted the IP-API resolve the IP that I got in the first link, but it does not work.
#!/usr/bin/python
import sys
import requests
print "Conectando com %s" % sys.argv[1]
Get_Skype = requests.get("http://api.predator.wtf/resolver/?arguments=%s" % sys.argv[1]).text
print "Entrando em %s" % Get_Skype
My_API = requests.get("http://ip-api.com/json/%s" % Get_Skype).text
print My_API
Command Line:
$ python script.py user_skype
The api returns:
{"message":"invalid query","query":"<ip>","status":"fail"}
The result of the request "http://api.predator.wtf/resolver/?arguments=user_skype" which is stored in Get_Skype is
Crap, No IP Was Found!
and not a valid IP which causes your api consider it a bad query (which it actually is). So you probably should first check this result being a valid IP address, before passing it to API.
If a valid username is entered, the result of the predator query has a trailing \ufeff character, which is BOM. See here how to deal with it.

Create Dialog Box in Blender using C or Python

How to make a dialog box (three options like quit/OK/Cancel) in blender and processing the text entered through python or in C. I'm unable to find any good tutorial on this. Any help....?
A quick and dirty way is to use zenity command (should be included by default in any python distribution). Try this short example script, it works in my Blender 2.69 on Ubuntu 14.04.
import bpy # bpy or bge does not matter
import subprocess as SP
# call an OS subprocess $ zenity --entry --text "some text"
# (this will ask OS to open a window with the dialog)
res=SP.Popen(['zenity','--entry','--text',
'please write some text'], stdout=SP.PIPE)
# get the user input string back
usertext=str(res.communicate()[0][:-1])
# adjust user input string
text=usertext[2:-1]
print("I got this text from the user: %s"%text)
See the zenity --help for more complex dialogs
blender doesn't offer things like dialogs.
Answers to This previous question on external modules may be helpful.
class DialogOperator(bpy.types.Operator)
bl_idname = "object.dialog_operator"
bl_label = "Save Before You QUIT!"
def execute(self, context):
message = " You didn't saved yet "
self.report({'INFO'}, message)
print(message)
return {'FINISHED'}
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
class DialogPanel(bpy.types.Panel)
bl_label = "Dialog"
bl_space_type = "VIEW_3D"
bl_region_type = "UI"
def draw(self, context):
self.layout.operator("object.dialog_operator")
But this is only for creating a dialog window. after this have to insert buttons in this code.If anyone known this try to post the answer. At the same time I'm also trying to sort out this.