I'm beginner in Python and I have problem to run my function in command line, through IDLE it's working, but I need to run it in command line, because I will have to make from it executable file...
So my problem... I have this
file name test.py
class A
def myFunction(a,b)
print a,b
myFunction calls Class, from IDLE it's enough to write myfunction(a,b), but from command line I don't know what to do
My goal is
to run function from command line with command: name_of_the_file arg1 arg2 --> test a b
I looked I think everywhere and tried everything, most common what I found was to add to my function this command
if __name__ == '__main__':
a = sys.argv[0]
b = sys.argv[1]
myFunction(a,b)
So it was
class A:
some process which calls myFunction
def myFunction(a,b)
print a,b
if __name__ == '__main__':
a = sys.argv[0]
b = sys.argv[1]
myFunction(a,b)
and then I called it from command line with test a b, but I got only errors
I use Python 2.7
Thank you for your help
Some issues with your code:
Python is case-sensitive. The keyword is class, not Class.
After the line class A there has to be a colon: class A:
If the function myFunction is supposed to be part of class A, it has to be indented:
class A:
def myFunction(a,b)
Methods of classes should have self as first parameter: def myFunction(self, a, b)
After def myFunction(self, a,b) there has to be a colon: def myFunction(self, a,b):
Your function must have at least one line of indented code following. If it is supposed to do nothing, you can use the keyword `pass:
def myFunction(self, a,b):
pass
If you want to use sys.argv you first have to import sys at the beginning of your code with import sys.
myFunction is part of a class, you first have to instantiate it to use the function:
Av = A()
Av.myFunction(a,b)
The first commandline argument is the second entry of sys.argv, not the first.
However it seems to me that you don't want a class anyway, so just write:
def myFunction(a,b):
pass
if __name__ == '__main__':
a = sys.argv[1]
b = sys.argv[2]
myFunction(a,b)
Also you call python scripts with python file.py arg1 arg2. If you want to omit python at the beginning then you can (in unix-like systems) add a shebang in the first line of the python-file: #!/usr/bin/env python. Then as long as the execution flag is set chmod +x file.py it may be called like ./file.py arg1 arg2.
Functions and Methods are 2 different things. Read more about it here. Methods must be called with their parent class as the first argument:
class Fruit:
def Taste(self):
print "Yuck!"
# Call it
Fruit().Taste()
You could pass argv in this manner:
MyClass(*args, **kwargs).MyMethod(argv, **kwargs)
EDIT
Am I right in assuming that you'd like to pass 2 (or more) arguments to the command line so that they could be passed on to a function and executed? If yes, I'll try something simple here:
from sys import argv
try:
a = argv[1]
b = argv[2]
except IndexError:
print "Enter both arguments"
class Integer:
def Check(self, z):
if int(z) < 0:
print z, "is a negative integer"
elif int(z) > 0:
print z, "is a positive integer"
else:
print z, "is not an integer"
# Make instance
myclass = Integer()
# Call methods
myclass.Check(a)
myclass.Check(b)
Related
I need to execute the class name with functions inside it and execute the functions inside the class individually on run time by passing arguments.
Python code saved as test.py
import sys
import threading
from threading import Thread
class test():
def func1(self):
print('hi im func1')
def func2(self):
print('hi im func2')
def func3(self):
print('hi im func3')
def runall(self):
if __name__ == '__main__':
Thread(target=self.func1).start()
Thread(target=self.func2).start()
Thread(target=self.func3).start()
if __name__ == '__main__':
try:
run = test()
run.runall()
globals()[sys.argv[1]]()
except KeyError:
raise KeyError('Invalid Function Name Passed in Argument! refer the code for valid Name.')
Trying to execute all functions inside class:
Runtime Execution: c:\ > python test.py test
Passed but gave error on
File "test.py", line 180, in
globals()sys.argv[2]
TypeError: 'test' object is not callable
Trying to execute only particular functions inside the class
Runtime Execution: c:\ > python test.py func1
Keyerror is getting thrown.
Can someone guide me on how to execute complete class and individual functions inside the class at runtime?
The first step works by me (on python 3.7.2)
> python3 test.py test
hi im func1
hi im func2
hi im func3
However this is triggered by the run.runall() statement. What version of Python do you run? don't you have another test variable in your work-space ?
For the second point, solution inspired by here, you could get the individual methods of the class running like this:
if __name__ == '__main__':
try:
run = test()
run.runall()
#globals()[sys.argv[1]]()
getattr(test(), sys.argv[1])()
except KeyError:
raise KeyError('Invalid Function Name Passed in Argument! refer the code for valid Name.')
result:
> python3 test.py func1
hi im func1
hi im func2
hi im func3
hi im func1
It worked for me Now I can Execute all Functions and separate functions individually. Thanks All For Your support and guide!!
if __name__ == '__main__':
try:
if sys.argv[2]=='test':
run = test()
run.runall()
else:
getattr(test(), sys.argv[2])()
except KeyError:
raise KeyError('Invalid Function Name Passed in Argument! refer the code for valid Name.')
Framework: Robot, Language: Python-3.7.1 Proficiency: Novice
I have a variable args=[] defined at class level. The values of the variables are being assigned from command prompt using module 'sys'
import sys
class Runner():
args = []
def argument_reader(self):
self.args = list(sys.argv)
def login(self):
return self.args[1], self.args[2]
I could print all the values of args as long as execution stays within the module. If I wanted to call the same values from other module, it does not return anything as the values are being cleared out from the memory. Since class variables are static by default in python, why system is not RETAINING the values?
cmd line>>py Runner.py testing test#123
For Example:
Calling method from same class:-
run = Runner()
run.argument_reader()
print(run.login())
Output>>> testing, testing#123
Calling the same method from another class:-
runn = Runner.Runner()
print(runn.login())
output>> IndexError: list index out of range
If you want a singleton-type value, change your code to look like this.
class Runner():
args = []
def argument_reader(self):
Runner.args = list(sys.argv)
def login(self):
return Runner.args[1], Runner.args[2]
Otherwise, you'll have to call argument_reader() on each instance.
The current code I have, allows the function to call the wrapper decorator, and uses the function name in its code. However, I'm looking for a way to give the function a 'alias' in a way as an argument. Here's the current code:
import os, sys
# Take user input
message = input('type command: ')
# Command wrapper
ALLCOMMANDS = {}
def command(function):
ALLCOMMANDS[function.__name__] = function
return function
# Commands
#command
def foo():
print("bar")
#command
def goo():
print('ber')
# Run appropriate command
if message in ALLCOMMANDS:
ALLCOMMANDS[message]()
For example I would want to be able to call the function by a name such as '!foo' from the user input, so maybe the argument would look like #command(name='!foo'), I just don't know where to go from there to use that argument in the decorator since it already has an argument.
I attempted
# Command wrapper
ALLCOMMANDS = {}
def command(name):
ALLCOMMANDS[name] = name
return name
but keep getting errors and I assume I am missing something
You should read up a bit more on python decorators. You're getting an error with:
def command(name):
ALLCOMMANDS[name] = name
return name
Because of the return name.
Decorators are just syntactic sugar. This:
#command
def foo():
print('bar')
Is equivalent to:
def foo():
print('bar')
foo = command(foo)
From this you can see why your original decorator works. At the end you return function.
Things get a little tricker when you have a decorator that takes arguments. Desugared the following:
#command('nickname')
def foo():
print('bar')
Looks like this:
def foo():
print('bar')
foo = command('nickname')(foo)
So, to write a decorator that takes arguments, the decorator needs to return a function that takes the function to decorate as an argument:
def command(nickname):
def wrapped(f):
ALLCOMMANDS[nickname] = f
return f
return wrapped
Also consider making ALLCOMMANDS an attribute on your command instead of a global (UPPER_SNAKE is usually reserved for constants):
def command(nickname):
def wrapped(f):
command._functions[nickname] = f
return f
return wrapped
command._functions = {}
How can I indent the print output on the command line from a class that is called? I can't edit the class file to add tabs to each print().
So I would call the imported class in mypythonthing.py:
print('Calling class')
MyClass()
All the print output would then be indented, or have something prepended to it.
e.g.
$ python mypythonthing.py
$ Running your python script...
$ Calling class
$ > The print output from MyClass is indented
$ > Exiting MyClass
$
Patch the built-in print function to prefix each line with your indentation.
import builtins
def print(*args, **kwargs):
builtins.print(" > ", *args, **kwargs)
If you can put the code that should be indented inside (one or more) functions, then you can use a decorator to wrap these functions.
Then any invocation of print inside these function will be indented.
Also, you will only need to declare this function in your main script, and not anywhere else.
Example -
import builtins
import another # for demo purposes only
# This will override the default `print` function.
# Invoking it as a decorator will automatically perform
# initialisation and cleanup. There is also never a need
# to modify this.
def indent(f):
def closure():
old = builtins.print
builtins.print = lambda x, *args, **kwargs: old("\t>", x, *args, **kwargs)
f()
builtins.print = old
return closure
some_number = "100"
# Example function, note decorator usage.
# This function may **not** take any parameters!
# It may however, use any variables declared before it.
#indent
def indentedStuffGoesHere():
print("Inside `indentedStuffGoesHere`")
print(some_number)
another.Foo().bar()
another.stuff()
print("entering special block")
indentedStuffGoesHere()
print("done")
another.py
def stuff():
print("TESTING stuff")
class Foo:
def bar(self):
print("HELLO FROM FOO")
Output:
entering special block
> Inside `indentedStuffGoesHere`
> 100
> HELLO FROM FOO
> TESTING stuff
done
i think what you might be looking for is textwrap:
textwrap docs
so as an example:
wrapper = textwrap.TextWrapper(width=preferredWidth, subsequent_indent='\t')
message = "asdf" * 50
print wrapper.fill(message)
Is there a way for a program to invoke another program in python?
Let me explain my problem:
I am building an application (program 1) , I am also writing a debugger to catch exceptions (program 2) in program 1 { a typical try : except: } block of code . Now I want to release program 2 so that for any application like prog 1 , prog 2 can handle exceptions ( making my work easier) . I just want prog 1 to use a simple piece of code like:
import prog2
My confusion stems from the fact as how can I do something like this , how can I invoke prog 2 in prog 1, ie it should function as all the code in prog 1 should run in the {try: (prog 1) , except:} prog 2 try block.
Any pointers on how I can do this or a direction to start would we very much appreciated.
Note: I am using python 2.7 and IDLE as my developer tool.
tried execfile() yet? Read up on it on how to execute another script from your script.
I think you need to think about classes instead of scripts.
What about this?
class MyClass:
def __init__(self, t):
self.property = t
self.catchBugs()
def catchBugs(self):
message = self.property
try:
assert message == 'hello'
except AssertionError:
print "String doesn't match expected input"
a = MyClass('hell') # prints 'String doesn't match expected input'
UPDATE
I guess you have something like this in your directory:
program1.py (main program)
program2.py (debugger)
__init__.py
Program1
from program2 import BugCatcher
class MainClass:
def __init__(self, a):
self.property = a
obj = MainClass('hell')
bugs = BugCatcher(obj)
Program2
class BugCatcher(object):
def __init__(self, obj):
self.obj = obj
self.catchBugs()
def catchBugs(self):
obj = self.obj
try:
assert obj.property == 'hello'
except AssertionError:
print 'Error'
Here we are passing the whole object of your program1 to the BugCatcher object of program2. Then we access some property of that object to verify that it's what we expect.