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.
Related
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:/')]
My Need is to execute a python script in my azure pipeline with additional command line arguments.
I'm able to run the script inline successfully with this code & the output I get is as expected:
1- for print ('Hello ', args.svc) as ('Hello, 'Service_De')
2- for print ('Hello ', args.env) as ('Hello, 'Dev')
- task: PythonScript#0
inputs:
scriptSource: inline
script: |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--svc")
parser.add_argument("--env")
args = parser.parse_args()
print ('Hello ', args.svc)
print ('Hello ', args.env)
arguments: --svc ${{parameters.service}}_${{parameters.environment}}
--env ${{parameters.environment}}
I have 2 issues that I need help with:
Issue #1:
When I separate my service & environment arguments and update my python task as a combination of both arguments, the script gives me an error
print ('Hello ', args.svc_args.env)
I am not able to format the python code properly. I ideally want the output as ('Helo','Service_Dev')
- task: PythonScript#0
inputs:
scriptSource: inline
script: |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--svc")
parser.add_argument("--env")
args = parser.parse_args()
print ('Hello ', args.svc_args.env)
arguments: --svc ${{parameters.service}}
--env ${{parameters.environment}}
Issue #2::
When I execute the same working code using the filepath option, it fails to execute and give me an error:
IOError: [Errno 2] No such file or directory: './group_vars/args.svc.yaml'
- task: PythonScript#0
inputs:
scriptSource: 'filePath'
scriptPath: "$(System.DefaultWorkingDirectory)/modify-config.py"
arguments: --svc ${{parameters.service}}_${{parameters.environment}}
#pythonInterpreter: # Optional
#workingDirectory: # Optional
#failOnStderr: false # Optional
displayName: 'Update Config files'
The modify-config.py has the following code:
#!/usr/bin/python
import os
import yaml
from jinja2 import Template
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--svc")
#parser.add_argument("--env")
args = parser.parse_args()
with open(r'./group_vars/args.svc.yaml') as file:
#value_list = yaml.load(file, Loader=yaml.FullLoader)
value_list = yaml.full_load(file)
You need to do something like this to get real directory path
See: Get parent of current directory from Python script
import os
import yaml
from jinja2 import Template
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--svc")
#parser.add_argument("--env")
args = parser.parse_args()
base_dir = Path(__file__).resolve().parent
file_path = os.path.join(base_dir, "group_vars/args.svc.yaml")
with open(file_path) as file:
#value_list = yaml.load(file, Loader=yaml.FullLoader)
value_list = yaml.full_load(file)
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()
I am working on a script under which some sub program will run.
for example test.py is the main program and under that test1.py, test2.py, test3.pl will run and I need to pass the arguments from the main program(test.py) to test1.py and test2.py program also.the arguments should be in unchanged condition. while passing to another program.
code: test.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")
commandLineArgumentParser.add_argument("-age","--age", help="age")
commandLineArguments = commandLineArgumentParser.parse_args()
fname = commandLineArguments.fname
lname = commandLineArguments.lname
age = commandLineArguments.age
print "%s%s%s" %(fname,lname,age)
I am running the program by the bellow commands :
python test.py -fname=abc -age=22 -lname='test a'
or
python test.py -fname="abc test" lname='val' -age=30
or
python test.py -age=45 -lname='abc aa' fname="abc"
or
python test.py -age=45 -lname="test"
now I want to grab the argument part in unchanged condition and put in one variable then we can easily pass the arguments to program easily.
For the first command the variable will hold
-fname=abc -age=22 -lname='test a'
for 2nd command
-fname="abc test" lname='val' -age=30
I was trying to grab the arguments using the bellow code but the quotas are missing by the script.
my_argu=''
if len(sys.argv) >1:
for x in sys.argv:
if x == sys.argv[0]:
continue
if x == sys.argv[len(sys.argv)-1]:
my_argu =my_argu+x
else:
my_argu = my_argu+x+' '
print "%s" %(my_argu)
for the
python test.py -fname="abc test" lname='val' -age=30
the output is :
abc testval30
-fname=abc test lname=val -age=30
as you can see quotas are missing. So I need help to solve it
Seems like you should pull these all together in one wrapper and call that instead.
# wrapper.py
import test, test1, test2, test3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-fname", "--fname",help="first name")
parser.add_argument("-lname","--lname", help="last name")
parser.add_argument("-age","--age", help="age")
cli_args = parser.parse_args()
test.run(cli_args)
test1.run(cli_args)
test2.run(cli_args)
test3.run(cli_args)
Then in each of your testN.pys...
# test.py
def run(cli_args):
print("Your name is {} {}".format(cli_args.fname, cli_args.lname))
# or whatever your program does....
Then do:
$ python wrapper.py --fname Adam --lname Smith
How can I print all arguments passed to a python script?
This is what I was trying:
#!/usr/bin/python
print(sys.argv[1:]);
update
How can I save them to a file?
#!/usr/bin/python
import sys
print sys.argv[1:]
file = open("/tmp/test.txt", "w")
file.write(sys.argv[1:])
I get
TypeError: expected a character buffer object
You'll need to import sys for that to work.
#!/usr/bin/python
import sys
print sys.argv[1:]
Example
:/tmp% cat foo.py
#!/usr/bin/python
import sys
print (sys.argv[1:]);
:/tmp% python foo.py 'hello world' arg3 arg4 arg5
['hello world', 'arg3', 'arg4', 'arg5']
the problem is with the list of args that write can't handle.
You might want to use:
file.write('\n'.join(sys.argv[1:]))
Your last line is wrong.
It should be:
file.writelines(sys.argv[1:])