some question when i use python_lib --click - python

here is my code from my demo.py:
import sys, click, os
#click.command()
#click.option('-f', '--file', required=True, help="file")
def tshark_do(file):
click.echo(file)
def two_function(DataFile="test"):
print(DataFile)
if __name__ == "__main__":
tshark_do()
two_function()
when i run python demo.py -f file, it just output file
seemd that the two_function() didn`t work
i guess that maybe it caused by #click.command() . but i don't know how to solve
please help your friend

Related

Redirect output from one python script to another argparse

This is probably a silly question but I've been struggling with this for a while now and I could not make it work. Basically what I am trying to do is use a script output with the command line passed arguments as an input for another script with arguments as well. This is my approach so far, I kind of feel that I am missing something though.
Let's suppose the following script1.py
# !/usr/bin/env python3
import argparse
import sys
def create_arg_parser():
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--number", type=int, help="numbers range")
return parser.parse_args()
def main_a():
nrange = parsed_args.number
l = [i for i in range(nrange)]
return l
if __name__ == "__main__":
parsed_args = create_arg_parser()
print(main_a())
and script2.py
# !/usr/bin/env python3
import os
import subprocess
import argparse
def create_arg_parser():
parser = argparse.ArgumentParser()
parser.add_argument("-o", "--outdir", type=str, help="outdir path")
return parser.parse_args()
def main_b():
# the -n argument here should be inherited from script1.py and not manually set to 5
process = subprocess.Popen(["python", "script1.py", "-n", "5"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = process.communicate() # let it run the list from script1.py
with open(os.path.join(parsed_args.outdir, "list.txt"), "w") as f:
f.write(output[0].decode('utf-8'))
if __name__ == "__main__":
parsed_args = create_arg_parser()
main_b()
This actually works (kinda actually), apart from the fact that I am getting the list outputted from script1.py written alongside the -n argument. What I am trying to do here is use the list created from script1.py as input in script2.py, but just passing the command line arguments once. So for instance, use or inherit the arguments used for script1.py in script2.py. I know this could be done putting all in the same script but this is just an example, I am trying to write a *gml graph in the real problem.
Any idea what I am missing here? Or is there any workaround or a simpler alternative to my approach?
While you can inherit arguments from another parser, for your use case it would be simpler to just define an argument explicitly, since you have to pass the value that results to the other script.
# !/usr/bin/env python3
import os
import subprocess
import argparse
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--number", type=int, help="numbers range")
parser.add_argument("-o", "--outdir", type=str, help="outdir path")
return parser.parse_args()
def main_b(args):
# the -n argument here should be inherited from script1.py and not manually set to 5
process = subprocess.Popen(["python", "script1.py", "-n", args.number], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = process.communicate() # let it run the list from script1.py
with open(os.path.join(parsed_args.outdir, "list.txt"), "w") as f:
f.write(output[0].decode('utf-8'))
if __name__ == "__main__":
parsed_args = parse_arguments()
main_b(parsed_args)
The alternative is that your first script has to expose its argument parser as a module-level attribute, and your second script would have to import the first. (That would, however, bypass the need to use subprocess to run the first script.
import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument("-n", "--number", type=int, help="numbers range")
def main_a(n):
l = [i for i in range(n)]
return l
if __name__ == "__main__":
nrange = parser.parse_args().number
print(main_a(nrange))
and
import os
import argparse
import script1
def parse_arguments():
parser = argparse.ArgumentParser(parents=[script1.parser])
parser.add_argument("-o", "--outdir", type=str, help="outdir path")
return parser.parse_args()
def main_b(parsed_args):
x = script1.main_a(parsed_args.number)
with open(os.path.join(parsed_args.outdir, "list.txt"), "w") as f:
f.write(str(x))
if __name__ == "__main__":
parsed_args = parse_arguments()
main_b(parsed_args)

python - adding a argument to execution script

consider I am having a following code in my bin as follows(filename: emp_dsb):
import sys
from employee_detail_collector.EmpCollector import main
if __name__ == '__main__':
sys.exit(main())
In my command line I will execute the "emp_dsb", so that above code will execute the main function from "employee_detail_collector.EmpCollector"
Code in (employee_detail_collector.EmpCollector) main():
def main():
try:
path = const.CONFIG_FILE
empdsb = EmpDashboard(path)
except SONKPIExceptions as e:
logger.error(e.message)
except Exception as e:
logger.error(e)
Now I need to add some argument here for emp_dsb, that is like "emp_dsb create_emp" should invoke a new set of functionalities for creating a employee, which is also needs to be added in same main()
someone look and let me know your ideas, If not clear let me know so that i will try to make it more clear.
the standard way to use command line arguments is to do this:
import sys
if __name__ == '__main__':
print(sys.argv)
read up on the doc of sys.argv.
then there are fancier ways like the built-in argparse and the 3rd party docopt or click.
I would personally use 'argparse' module.
Here is the link to a dead simple code sample.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print(args.echo)

return value from one python script to another

I have two files: script1.py and script2.py. I need to invoke script2.py from script1.py and return the value from script2.py back to script1.py. But the catch is script1.py actually runs script2.py through os.
script1.py:
import os
print(os.system("script2.py 34"))
script2.py
import sys
def main():
x="Hello World"+str(sys.argv[1])
return x
if __name__ == "__main__":
x= main()
As you can see, I am able to get the value into script2, but not back to script1. How can I do that? NOTE: script2.py HAS to be called as if its a commandline execution. Thats why I am using os.
Ok, if I understand you correctly you want to:
pass an argument to another script
retrieve an output from another script to original caller
I'll recommend using subprocess module. Easiest way would be to use check_output() function.
Run command with arguments and return its output as a byte string.
Sample solution:
script1.py
import sys
import subprocess
s2_out = subprocess.check_output([sys.executable, "script2.py", "34"])
print s2_out
script2.py:
import sys
def main(arg):
print("Hello World"+arg)
if __name__ == "__main__":
main(sys.argv[1])
The recommended way to return a value from one python "script" to another is to import the script as a Python module and call the functions directly:
import another_module
value = another_module.get_value(34)
where another_module.py is:
#!/usr/bin/env python
def get_value(*args):
return "Hello World " + ":".join(map(str, args))
def main(argv):
print(get_value(*argv[1:]))
if __name__ == "__main__":
import sys
main(sys.argv)
You could both import another_module and run it as a script from the command-line. If you don't need to run it as a command-line script then you could remove main() function and if __name__ == "__main__" block.
See also, Call python script with input with in a python script using subprocess.

distutils - How to add a .pyw script if windows

I am distributing a simple library/application which includes a script with GUI. Under windows I want this to be run by pythonw.exe, preferrably by making it a .pyw file.
root/
lib/
lib.py
guiscript.py
setup.py
I want the user to be able to install guiscript in any path.
I stole this hook from this question:
from distutils.core import setup
from distutils.command.install import install
import os, sys
class my_install(install):
def run(self):
install.run(self)
try:
if (sys.platform == "win32") and sys.argv[1] != "-remove":
os.rename("guiscript.py",
"guiscript.pyw")
except IndexError:pass
setup(...
cmdclass={"install": my_install})
But this doesn't work because it changes the name of guiscript.py in the source folder, because the path is relative to setup.py.
Is there a reasonable way to get the script install-path, or alternativly a simple way to find guiscript.py (it's not given it's in PYTHONPATH).
So because I don't have 50 karma i can't answer my own post in 7 hours but here it is:
Okay, I found the solution. I can delete the question if you want, but for now I'll keep it in case someone else has the same question.
from distutils.core import setup
from distutils.command.install_scripts import install_scripts
import os, sys
class my_install(install_scripts):
"""Change main script to .pyw after installation.
If sys.argv == '-remove'; it's ran as uninstall-script.
Override run() and then call parent."""
def run(self):
install_scripts.run(self)
try:
if (sys.platform == "win32") and sys.argv[1] != "-remove":
for script in self.get_outputs():
if script.endswith("guiscript.py"):
os.rename(script, script+"w")
except IndexError:pass
setup(...
cmdclass={"install_scripts": my_install}
)

ArgumentParser -h (help) will not work

I cannot get ArgumentParser to work. What's wrong with the following:
import argparse
parser=argparse.ArgumentParser(description='''I wish this description would output''',
epilog='''Please out the epilog''')
parser.add_argument('-l', type=str, default='info', help='logging level. Default is info. Use debug if you have problems.')
args=parser.parse_args()
def main():
print("goodbye")
if __name__ == "__main__":
#main
main()
When I run myscript -h I see no help.
I am running Python 2.7 on Windows 7. I have Python on my path and also pathext set as:
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.py
The argsparse code never actually gets executed. By executing the script from the command line, you're calling main(), which simply prints and exits. You have to call parse_args() in the main() function for this to work.
import argparse
# Personally, I think these belong in the main()
# function as well, but they don't need to be.
parser = argparse.ArgumentParser(
description="I wish this description would output",
epilog="Please out the epilog"
)
parser.add_argument(
"-l",
type=str,
default="info",
help="logging level. Default is info. Use debug if you have problems."
)
def main():
args = parser.parse_args() # Parses arguments
print("goodbye")
if __name__ == "__main__":
main() # Calls main
Produces:
~/Desktop $ python untitled.py --help
usage: untitled.py [-h] [-l L]
I wish this description would output
optional arguments:
-h, --help show this help message and exit
-l L logging level. Default is info. Use debug if you have problems.
Please out the epilog
jcollado claims your code worked fine on Ubuntu--I find this very curious.
If you run this script from the command line you're going to just print 'goodbye', put the argparse code after if __name__ == "__main__":.
OK weird answer for this. The problem was resolved by calling the program as:
python myscript.py -h
If you add python to your path, set file associations and then just do:
myscript.py -h
it will not pick up the -h

Categories