Use argparse module with argument for a function - python

I'm trying to execute my function play()
import argparse
from num2words import num2words
def play():
parser = argparse.ArgumentParser()
parser.add_argument("--b", default=100,type=int,help="b")
args = parser.parse_args()
for file in reversed(range(file)):
print(num2words(iteration) + " there are")
print(num2words(iteration) + " there are")
I keep running in python commandline:
>>> import myfile
>>> file.play()
but it keeps using the default=100, how can i specify the argument --b 10 for example?

Change your program to:
import argparse
from num2words import num2words
def play():
parser = argparse.ArgumentParser()
parser.add_argument("--b", default=100,type=int,help="b")
args = parser.parse_args()
for file in reversed(range(file)):
print(num2words(iteration) + " there are")
print(num2words(iteration) + " there are")
if __name__ == '__main__':
play()
and add all the missing code not shown in your question.
On the command line:
python my_file_name.py --b 10
The command line is not the interactive Python interpreter, i.e. the >>> prompt. Type exit() and then enter this line. The command line is the on Linux/Mac OS X for example the bash shell; on Windows the "DOS box".
For interactive work try:
>>> import sys
>>> sys.argv.extend(['--b', '10'])
>>> import myfile
>>> file.play()

Related

Python, argument parameter error with sys module

I am trying to get arguments in python with the sys module.
Here my code:
import sys
import os
path = sys.argv[0]
argument = sys.argv[1]
print("Hello, Temal Script installed.")
if argument == "-h":
os.system("cls")
print("Available comamnds:\n-h = help\n-i = information\n-v = version")
if argument == "-i":
os.system("cls")
print("This is a script written by Temal")
if argument == "-v":
os.system("cls")
print("Version: 1.0")
If I enter in the cmd "main.py -h" it works great. But if I enter only "main.py" it prints me out an error:
Traceback (most recent call last):
File "C:\Windows\cmd.py", line 5, in <module>
argument = sys.argv[1]
IndexError: list index out of range
I know why i get this error, because in the list will be only one item (the path) because i dont enter a second argument. But how can I do that the script ignores this error if no second argument is set? If someone enters main.py without an argument I only want to print out this text: Hello, Temal Script installed.
Or maybe is there something like in PHP "isset"?
I am also new to this topic so please answer simple and not complicated.
Thanks!
Need to check the length of the sys.argv variable.
import sys
import os
path = sys.argv[0]
if len(sys.argv) > 1:
argument = sys.argv[1]
print("Hello, Temal Script installed.")
if argument == "-h":
os.system("cls")
print("Available comamnds:\n-h = help\n-i = information\n-v = version")
elif argument == "-i":
os.system("cls")
print("This is a script written by Temal")
elif argument == "-v":
os.system("cls")
print("Version: 1.0")
Also, look at argparse module.
import argparse
import os
parser = argparse.ArgumentParser(description="My App")
parser.add_argument('-i', '--info', action='store_true',
help="show information")
parser.add_argument('-v', '--version', action='store_true',
help="show version")
args = parser.parse_args()
if args.info:
os.system("cls")
print("This is a script written by Temal")
elif args.version:
os.system("cls")
print("Version: 1.0")
Run main.py -h outputs:
usage: help.py [-h] [-i] [-v]
My App
optional arguments:
-h, --help show this help message and exit
-i, --info show information
-v, --version show version

How to make argparse accept directories in script?

Currently, this script only accepts files as input (via argparse). I am trying to edit it so it will also accept paths as input. How would I do this?
Script (irrelevant parts omitted):
#!/usr/bin/env python
import argparse
import sys
def main(args=None):
parser = argparse.ArgumentParser()
parser.add_argument("input", nargs="+", metavar="INPUT")
parser.add_argument("-o", "--output")
options = parser.parse_args(args)
for path in options.input:
if options.output and not os.path.isdir(options.output):
output = options.output
font = TTFont(path, fontNumber=options.face_index)
if __name__ == "__main__":
sys.exit(main())
Say goodbye to os.path and welcome the pathlib.
>>> import pathlib
>>> p = pathlib.Path("")
>>> p
PosixPath('.')
>>> p.absolute()
PosixPath('/storage/emulated/0')
>>> p = p.joinpath("log/GearLog")
>>> p
PosixPath('log/GearLog')
>>> p.is_dir()
True
>>> for file in (f for f in p.iterdir() if f.suffix == ".log"):
... print(file.name)
...
GearN_dumpState-CM.log
GearN_dumpState-CM_old.log
GearN_dumpState-WIFI_P2P.log
GearN_dumpState-HM.log
GearN_dumpState-HM_old.log
GearN_dumpState-NS_HM.log
GearN_dumpState-NS_HM_old.log
GearN_dumpState-NS_GO.log
GearN_dumpState-NS_GO_old.log
GearN_dumpState-ESIM.log
GearN_dumpState-CS.log
GearN_dumpState-CT.log
GearN_dumpState-SM.log
GearN_dumpState-WF.log
GearN_dumpState-STICKER.log
GearN_dumpState-SEARCH.log
GearN_dumpState-WF_old.log
>>>
With this you can just pass any sort of file/directory strings and check if it's directory or file, and whether it exists or not. I use this to pass path parameter via argparse.
You didn't clearly stated that you know existence of pathlib and you know you will have to use this, I omitted how this could be used in argparse and put more effort demonstrating how convenientpathlib is, and how it is used in general.
As you now stated that you do know it's existence, here's how It's actually done.
import argparse
import pathlib
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("path", nargs="+", type=pathlib.Path)
args = parser.parse_args()
print([path.absolute() for path in args.path])
> scratch.py ./ X:\ Z:\
[WindowsPath('[REDACTED]/scratches'), WindowsPath('X:/'), WindowsPath('Z:/')]

Run Python file from CMD with extra things

I donĀ“t know, how to run a python file (python test.py) with extra stuff, like this:
python test.py "hello world"
python [FILE] [SAY]
What i want:
def something(say):
print(say)
A simple example of using argparse:
import argparse
cmd_parser = argparse.ArgumentParser()
cmd_parser.add_argument('SAY', help= 'The string you want to print on the
terminal')
args = cmd_parser.parse_args()
print(args.SAY)
I found a solution (a long time ago btw):
import sys
sys.argv
Thats it! It returns a list with all arguments:
C:\Programs >>> test.py-t "Hello, World!" start
["test.py","-t","Hello World","start"]

Unable to get the value of a command argument using argparse

I'm trying to parse the command line arguments in a very simple way:
$ python main.py --path /home/me/123
or
$ python main.py --path=/home/me/123
And then:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--path')
args = parser.parse_args()
And args returns nothings:
(Pdb) args
(Pdb) args.path
How can I access the value of --path?
You can print args.path and it will show your line argument. For more details you can check the below link for more details about argparse
Argparse Tutorial
You can also use sys to parse your command line arguments, such as
>>> import sys
>>> path = sys.argv[1] # sys.argv always start at 1
>>> print path
Check the below link for more details.
Python Command Line Arguments
Hope it helps.
It works fine for me...
>>> args
Namespace(path='/home/me/123')
So you can access it via args.path

How to pass argparse arguments to another python program?

I am tying a script which will pass argparse arguments to another python
1st script : t.py
import argparse
import subprocess
import os
commandLineArgumentParser = argparse.ArgumentParser()
commandLineArgumentParser.add_argument("-fname", "--fname", help="first name")
commandLineArgumentParser.add_argument("-lname","--lname", help="last name")
commandLineArguments = commandLineArgumentParser.parse_args()
fname = commandLineArguments.fname
lname = commandLineArguments.lname
print "%s\n%s" %(fname,lname)
os.system("python test1.py")
code for test1.py is bellow
import argparse
import os
print "test abc"
I want to pass lname and fname values to test1.py .is their their any way to do that.
in the above code if I ran
python t.py -fname ms lname = dhoni
then the output is
ms
dhoni
test abc
But I want the output to be like bellow
ms
dhoni
ms
dhoni
Try this for test1.py:
from sys import argv
print "%s\n%s" % (argv[1], argv[2])
Hum I don't understand why you are trying to do that, but you really already have all that is required to achieve this task :
First python script (I call it sof.py):
import argparse
import subprocess
import os
commandLineArgumentParser = argparse.ArgumentParser()
commandLineArgumentParser.add_argument("-fname", "--fname", help="first name")
commandLineArgumentParser.add_argument("-lname","--lname", help="last name")
commandLineArguments = commandLineArgumentParser.parse_args()
fname = commandLineArguments.fname
lname = commandLineArguments.lname
print("%s\n%s" %(fname,lname))
command = "python sof2.py {arg1} {arg2}".format(arg1=fname, arg2=lname)
os.system(command)
Second python scrit (sof2.py here)
import argparse
import subprocess
import os
commandLineArgumentParser = argparse.ArgumentParser()
commandLineArgumentParser.add_argument("fname")
commandLineArgumentParser.add_argument("lname")
commandLineArguments = commandLineArgumentParser.parse_args()
fname = commandLineArguments.fname
lname = commandLineArguments.lname
print "%s\n%s" %(fname,lname)
This give me the following execution :
python3 sof.py -fname foo -lname bar
foo
bar
foo
bar
NB : I use python3 but if you have to use python2 this code is still correct, just remove ( and ) around the print
you can modify test1.py to include t.py and directly access the argparse variables.
test1.py
import t.py
print t.fname, t.lname
Change your test1.py to:
import argparse
import os
import sys
print sys.argv
print "test abc"
And call your test1.py from t.py as:
os.system("python test1.py vv gg hh")
Now your args vv gg hh are available in test1.py.

Categories