Run Python file from CMD with extra things - python

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"]

Related

Call a Python function and pass windows parameters from cmd.exe

I have a Python function that I want to run from the context-menu. I am using the Windows Registry to call the function when a file is right clicked, and I want the function to receive the file selected.
The context menu item looks something like the Random Commands option.
The function I wish to run is foo1() in the file test1:
# in script test1.py
def foo1():
import sys
print(sys.argv)
I tried approaching the problem using the python -c switch to directly call the function:
python -c "import test1; test1.foo1()" %1
However, the value of sys.argv after selecting the file and executing is ['-c'], which doesn't include the file selected.
I also tried using an argument parser to dynamically import and run the function:
# in file registry_parser.py
import argparse
import os
import sys
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--func_name')
parser.add_argument('-f', '--file_name')
parser.add_argument('-p', '--file_path')
args = vars(parser.parse_args())
sys.path.insert(0, args['file_path'])
exec(f"import {args['file_name']}")
exec(f"{args['file_name']}.{args['func_name']}(sys.argv)")
And the function I would call from the registry is (paths simplified):
registry_parser.py --func_name foo1 --file_name test1 --file_path "[PATH TO registry_parser.py]" %1
However, I either get an error registry_parser.py: error: unrecognized arguments: %1 or the "%1" is parsed quite literally and ends up as a value in sys.argv.
Any help is appreciated.
So on all the forums I asked I never received a correct answer, but I found this Reddit Post that has an example to a solution. Hope this helps someone else.

how to pass file as argument in python script using argparse module?

I am writing an automation script in python using argparse module in which I want to use the -s as an option which takes file/file path as an argument. Can somebody help me to do this?
Example: ./argtest.py -s /home/test/hello.txt
Just do this:
import argparse
parser = argparse.ArgumentParser(description="My program!", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument("-s", type=argparse.FileType('r'), help="Filename to be passed")
args = vars(parser.parse_args())
open_file = args.s
If you want to open the file for writing, just change r to w in type=argparse.FileType('r'). You could also change it to a, r+, w+, etc.
You can use
import argparse
parse = argparse.ArgumentParser()
parse.add_argument("-s")
args = parse.parse_args()
# print argument of -s
print('argument: ',args.s)
Suppose the above code is stored in the file example.py
$ python example.py -s /home/test/hello.txt
argument: /home/test/hello.txt
You can click here(Python3.x) or here(Python2.x) to learn more.

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

Python - passing parameters in a command line app

I need to write a command line application, like a shell. So it will include commands etc. The thing is I don't know how to pass parameters to the funcions in a module. For example:
User writes: function1 folder1
Program should now pass the 'folder1' parameter to the function1 function, and run it. But also it has to support other functions with different parameters ex:
User input: function2 folder2 --exampleparam
How to make this to work? I mean, I could just write a module, import it in python and just use the python console, but this is not the case. I need a script that takes command input and runs it.
I tried to use eval(), but that doesn't solve the problem with params. Or maybe it does but I don't see it?
The first part of your problem -- parsing the command line -- can be solved with argparse.
The second part -- converting the string name of a function into a function call -- can be done with exec or a dispatching dict which maps from strings to function objects.
I would recommend NOT using exec for this, since
allowing a user to call arbitrary Python functions from the command line might be dangerous. Instead, make a whitelist of allowable functions:
import argparse
def foo(path):
print('Running foo(%r)' % (path, ))
def bar(path):
print('Running bar(%r)' % (path, ))
dispatch = {
'foo': foo,
'bar': bar,
}
parser = argparse.ArgumentParser()
parser.add_argument('function')
parser.add_argument('arguments', nargs='*')
args = parser.parse_args()
dispatch[args.function](*args.arguments)
% test.py foo 1
Running foo('1')
% test.py bar 2
Running bar('2')
% test.py baz 3
KeyError: 'baz'
The above works when the command is typed into the command-line itself. If the command is being typed into stdin, then we'll need to do something a bit different.
A simple way would be to call raw_input to grab the string from stdin. We could then parse the string with argparse, as we did above:
shmod.py:
import argparse
def foo(path):
print('Running foo(%r)' % (path, ))
def bar(path):
print('Running bar(%r)' % (path, ))
dispatch = {
'foo': foo,
'bar': bar,
}
def parse_args(cmd):
parser = argparse.ArgumentParser()
parser.add_argument('function')
parser.add_argument('arguments', nargs='*')
args = parser.parse_args(cmd.split())
return args
main.py:
import shmod
while True:
cmd = raw_input('> ')
args = shmod.parse_args(cmd)
try:
shmod.dispatch[args.function](*args.arguments)
except KeyError:
print('Invalid input: {!r}'.format(cmd))
Another, more sophisticated way to handle this is to use the cmd module, as #chepner mentioned in the comments.
from cmd import Cmd
class MyInterpreter(Cmd):
prompt = '> '
def do_prompt(self, line):
"Change the interactive prompt"
self.prompt = line + ': '
def do_EOF(self, line):
return True
def do_foo(self, line):
print('Running foo {l}'.format(l=line))
def do_bar(self, line):
print('Running bar {l}'.format(l=line))
if __name__ == '__main__':
MyInterpreter().cmdloop()
For more information on how to use the cmd module, see Doug Hellman's excellent tutorial.
Running the code above yields a result like this:
% test.py
> foo 1
Running foo 1
> foo 1 2 3
Running foo 1 2 3
> bar 2
Running bar 2
> baz 3
*** Unknown syntax: baz 3
optparse is deprecated since python 2.7 and anyway argparse is much more flexible.
The approach of unutbu is safe, but in case you provide whitelist, I would suggest you to let the user know which functions are accepted
dispatch = {
'foo': foo,
'bar': bar,
}
parser = argparse.ArgumentParser()
parser.add_argument('function', choices=dispatch.keys() )
FYI: if the parsing is not too complicated, docopt looks like a very nice package
How about sys.argv? For more advanced stuff check out argsparse. optparse seems depreciated now, but there's a lot of answers here about this question.
Take a look at the optparse module in python. It's exactly what you would need:
http://docs.python.org/2/library/optparse.html
Or you can write your own custom opt-parser (minimalistic though)
def getopts(argv):
opts = {}
while argv:
if argv[0][0] == '-': # find "-name value" pairs
opts[argv[0]] = argv[1] # dict key is "-name" arg
argv = argv[2:]
else:
argv = argv[1:]
return opts
if __name__ == '__main__':
from sys import argv # example client code
myargs = getopts(argv)
# DO something based on your logic here
But in case your script needs to run on python 3 and beyond, you need to consider argparse module.\
Hope that helps.
Take a look at optparse . This can help passing and receiving shell style parameters to python scripts.
Update:
Apparently optparse is deprecated now and argparse is now preferred option for parsing command line arguments.
import sys
def main(arg):
return arg
print main(sys.argv[1])
where sys.argv[0] is the .py file you're running, and all the ones after it would be each argument. you could check the length of the list, then iterate through it, and parse them as necessary and pass the correct things to each function

How can I print all arguments passed to a python script?

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:])

Categories