I want to define a function such that I want it to accept command line arguments
below is my code
def tc1(resloc):
from uiautomator import Device;
'Do some activity'
with open(resloc, 'a') as text_file:
text_file.write('TC1 PASSED \n')
text_file.close()
else:
with open(resloc, 'a') as text_file:
text_file.write('TC1 FAILED \n')
text_file.close()
if __name__ == '__main__':
tc1("C:\\<pathtoautomation>\\Results\results.txt")
Now when I execute the same using command line from python it continues to refer to the path mentioned here tc1("C:\\<pathtoautomation>\\Results\results.txt") and doesn't consider what I pass in the runtime from the command line
\Scripts>python.exe trail.py C:\\<pathtoautomationresults>\\Results\results.txt
What you are looking is sys.argv
The list of command line arguments passed to a Python script. argv[0]
is the script name (it is operating system dependent whether this is a
full pathname or not). If the command was executed using the -c
command line option to the interpreter, argv[0] is set to the string
'-c'. If no script name was passed to the Python interpreter, argv[0]
is the empty string.
To loop over the standard input, or the list of files given on the
command line, see the fileinput module.
You use it like:
import sys
def main(argv):
# do something with argv.
if __name__ == "__main__":
main(sys.argv[1:]) # the argv[0] is the current filename.
and call it using
python yourfile.py yourargsgohere
Check out a more detailed use here.
You need to use sys.argv to get command line parameters.
in your code it could look like this:
import sys
... # other stuff
if __name__ == '__main__':
tc1(sys.argv[1])
There are many tutorials out there that help you use sys.argv
Related
I have searched SO but couldn't find an asnwer.
I want to invoke a python script(child script) from another python script(main script). I cannot pass arguments from parent to child?
I am expecting "subprocess launched: id1-id2" from the console.
But what I am getting is "subprocess launched:test-default". The subprocess is using the default parameters instead of receiving parameters from the parent script.
# parent
import subprocess
subprocess.call(['python', 'child.py', 'id1', 'id2'])
# script name: child.py
def child(id, id2):
print ('subprocess launched: {}-{}'.format(str(id), id2))
if __name__ == '__main__':
main(id='test', id2='default')
The parameters that you pass to a Python process are stored in sys.argv [Python-doc]. This is a list of parameters, that works a bit similar to $# in bash [bash-man] for example.
Note that argv[0] is not the first parameter, but the name of the Python script you run, as is specified by the documentation:
argv[0] is the script name (it is operating system dependent whether this is a full pathname or not).
The remaining parameters are the parameters passed to the script.
You can thus rewrite your child.py to:
# script name: child.py
from sys import argv
def child(id, id2):
print ('subprocess launched: {}-{}'.format(str(id), id2))
if __name__ == '__main__':
child(id=argv[1], id2=argv[2])
I am new to Python. I want to run a software in interactive mode. In the manual it says the usage
python experiment.py --config config.yaml --out result/
The question is, how can I supply the command line arguments to experiment.py in interactive mode?
The commandline arguments that e.g. optparse and argparse uses are taken by default from sys.argv element 1 and up. You can always do:
import sys
sys.argv[1:] = ['--config', 'config.yaml', '--out', 'result/']
Although e.g. in argparse you can provide the arguments explicitly to .parse_args() as well and then that method will not inspect sys.argv
If I understood you correctly you need something like this:
while True:
query = raw_input("> ")
if query == "exit":
break
# do something useful
I am trying to pass argument from batch file to python as following. It seems nothing has passed to 'sample' variable. My questions are
How to get argument properly?
How to check null point error when I am running .bat to execute this python? I may not be able to see the console log in IDE while executing
My batch file (.bat)
start python test.py sample.xml
My python file (test.py)
def main(argv):
sample = argv[1] #How to get argument here?
tree = ET.parse(sample)
tree.write("output.xml")
if __name__ == '__main__':
main(sys.argv[1:])
In your code, you're skipping the first argument twice.
main gets called with sys.argv[1:], skipping the first argument (program name); but then main itself uses argv[1]... skipping its first argument again.
Just pass sys.argv untouched to main and you'll be fine, for example.
Or, perhaps more elegantly, do call main(sys.argv[1:]), but then, in main, use argv[0]!
Use argparse https://docs.python.org/3/library/argparse.html
Eg: In your python file
import argparse
parser = argparse.ArgumentParser(description='Your prog description.')
parser.add_argument('-f','--foo', help='Description for foo argument', required=True)
:
:
args = parser.parse_args()
Inside your bat file
python prog.py -f <foo arg here>
So I have a fully functional py script running on Ubuntu 12.04, everything works great. Except I don't like my input methods, it's getting annoying as you'll see below. Before I type out the code, I should say that the code takes two images in a .img format and then does computations on them. Here's what I have:
import os
first = raw_input("Full path to first .img file: ")
second = raw_input("Full path to second .img file: ")
print " "
if os.path.exists(first) == True:
if first.endswith('.img') == False:
print 'You did not give a .img file, try running again'
os.sys.exit()
elif os.path.exists(second) == True:
if second.endswith('.img') == False:
print 'You did not give a .img file, try running again'
os.sys.exit()
else:
print "Your path does not exist, probably a typo. Try again"
os.sys.exit()
Here's what I want; I want to be able to feed python this input straight from the Terminal. In other words, I want to be able to input in the terminal something like
python myscript.py with the two images as input
This way I could make use of the terminal's tab-key shortcut when specifying paths and stuff. Any ideas/suggestions?
EDIT: Ok so I looked into the parsing, and I think I got down how to use it. Here's my code:
import argparse
import nipy
parser = argparse.ArgumentParser()
parser.add_argument("-im", "--image_input", help = "Feed the program an image", type = nipy.core.image.image.Image, nargs = 2)
however now I want to be able to use these files in the script by saying something like first = parser[0] second = parse[1] and do stuff on first and second. Is this achievable?
You want to parse the command line arguments instead of reading input after the program starts.
Use the argparse module for that, or parse sys.argv yourself.
Seeing that the parsing code already exists, all you need to do is accept command-line arguments with Python's sys module:
import sys
first = sys.argv[1]
second = sys.argv[2]
Or, more generally:
import os
import sys
if __name__ == '__main__':
if len(sys.argv) < 2:
print('USAGE: python %s [image-paths]' % sys.argv[0])
sys.exit(1)
image_paths = sys.argv[1:]
for image_path in image_paths:
if not os.path.exists(image_path):
print('Your path does not exist, probably a typo. Try again.')
sys.exit(1)
if image_path.endswith('.img'):
print('You did not give a .img file, try running again.')
sys.exit(1)
NOTES
The first part of the answer gives you what you need to accept command-line arguments. The second part introduces a few useful concepts for dealing with them:
When running a python file as a script, the global variable __name__ is set to '__main__'. If you use the if __name__ == '__main__' clause, you can either run the python file as a script (in which case the clause executes) or import it as a module (in which case it does not). You can read more about it here.
It is customary to print a usage message and exit if the script invocation was wrong.
The variable sys.argv is set to a list of the command-line arguments, and its first item is always the script path, so len(sys.argv) < 2 means no arguments were passed. If you want exactly two arguments, you can use len(sys.argv) != 3 instead.
sys.argv[1:] contains the actual command-line arguments. If you want exactly two arguments, you can reference them via sys.argv[1] and sys.argv[2] instead.
Please don't use if os.path.exists(...)==True and if string.endswith(...)==True syntax. It is much clearer and much more Pythonic to write if os.path.exists and if string.endswith(...) instead.
Using exit() without an argument defaults to exit(0), which means the program terminated successfully. If you are exiting with an error message, you should use exit(1) (or some other non-zero value...) instead.
What you want to do is take in command line parameters, and the best way to do that is using a nifty module called argparse. I have listed below a good resource on how to install and use it.
Here is a great resource for argparse. It is a module used to take command line arguments.
You can probably use sys.argv:
import sys
first = sys.argv[1]
second = sys.argv[2]
Don't forget to check len(sys.argv) before.
i would like to start a python file (.py) with arguments and receive the output of it after it is finished. i have already heard about "popen" and "subprocess.call" but i could not find any tutorials how to use them
does anyone know a good tutorial?
You don't need them ; just launch your file as a program giving argument like
./main.py arg1 arg2 arg3 >some_file
(for that your file must begin with something like #!/usr/bin/env python)
Using sys module you can access them :
arg1 = sys.argv[1]
arg2 = sys.argv[2]
arg3 = sys.argv[3]
i would like to start a python file (.py) with arguments and receive the output of it after it is finished.
Step 1. Don't use subprocess. You're doing it wrong.
Step 2. Read the Python file you want to run. Let's call it runme.py.
Step 3. Read it again. If it's competently written, there is a block of code that starts if __name__ == "__main__":. What follows is the "external interface" to that file. Since you provided no information in the question, I'll assume it looks like this.
if __name__ == "__main__":
main()
Step 4. Read the "main" function invoked by the calling script. Since you provided no information, I'll assume it looks like this.
def main():
options, args = parse_options()
for name in args:
process( options, file )
Keep reading to be sure you see how parse_options and process work. I'll assume parse_options uses optparse.
Step 5. Write your "calling" script.
import runme
import sys
import optparse
options = options= optparse.Values({'this':'that','option':'arg','flag':True})
with open( "theoutput.out", "w" ) as results:
sys.stdout= results
for name in ('some', 'list', 'of', 'arguments' ):
runme.process( options, name )
This is the correct way to run a Python file from within Python.
Actually figure out the interface for the thing you want to run. And run it.
runme.py
print 'catch me'
main.py
import sys
from StringIO import StringIO
new_out = StringIO()
old_out = sys.stdout
sys.stdout = new_out
import runme
sys.stdout = old_out
new_out.seek(0)
print new_out.read()
and...
$ python main.py
catch me
Unless you mean you want to start the Python file from within Python? In which case it's even nicer:
import nameOfPythonFile