Add functions to path - Python - python

I have just started to use Python (I am used to MATLAB).
How should I add a function to path? In matlab you right click on the function and you can add or remove from path.
For instance, a simple program to evaluate the power of a number:
As you can see the original program and the function are in the same folder, however the function seems to have an error. What am I doing wrong?
Thanks

If you hover the mouse over the redlined identifier, PyCharm will tell you what it thinks is wrong (and give you a balloon to fix it). Alternatively you can press F2 to go to the next error.
In this case it is complaining that you're not following PEP8 conventions for function and argument names.
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
Variable names follow the same convention as function names.
From: https://www.python.org/dev/peps/pep-0008/#function-and-variable-names
In addition, you need to import names before you can use them, ie. in app.py:
from . import POWER
a = 3
print(POWER.POWER(a))
or
from .POWER import POWER
a = 3
print(POWER(a))
Since you're using PyCharm, you can put your cursor on the name in app.py that is not recognized and press alt+enter and chose the option to "import this name".

Hi function in python define like this :
def <funcname>(<arguments>):
statement....
If you want to call function use:
<funcname>(<arguments>)
your fucntion:
def power(num):
return num**2
print(power(2))
output:
4
but if you want to add it to another .py file
write this code in your app.py
from .power import power
print(power(2))

Python has a built-in hierarchy of import protocols that I would suggest getting to know. To accomplish what you're trying to do, if you (after cleaning up a bit of syntax, and remove the space between POWER and the brackets, and add a colon to the end of the function definition, ie def power(Num): ) you can access the function from file POWER by adding to the top of app:
from POWER import power

Related

is it possible to access variable (local or global) main.py when running imported module function? [duplicate]

This question already has answers here:
Sharing scope in Python between called and calling functions
(5 answers)
Closed 1 year ago.
e.g. I have 2 py script, namely main.py and stringhelper.py.
Since print(f'{student_{i}_{j}}') cannot be read in IDE if variable student_1_2 exist and if i=1,j=2,
I want to make a function that can print 'x{a{h}b{i}c{j}z}y' by changing the string to
exec('''temp_s = 'a{}b{}c{}z'.format(h,i,j)''') # where I suppose e.g. h can refer to main.h but cannot
exec('''print('x{}y'.format(f'{temp_s}')'''
In
stringhelper.py
import re
def execprintf(s):
if s.find('{')<0:
print(s)
exec('''print(s)''')
else:
# use re to do sth to recongize {...{...{ case
if conditionA: # {...{...{ case
print('warning for input s')
elif conditionB: # ... {...{ case
# not finished
# not writing as I meet some problem for simple '{h}' case below
pass
else:
ss = re.split('{|}',s)
ss_even = ss[0::2]
ss_odd = ss[1::2]
s_wo_args = '{}'.join(ss_even)
s_args = ', '.join(ss_odd)
exec('''print(s_wo_args.format('''+s_args+'''))''')
In
main.py
from stringhelper.py import execprintf
h = 1
execprintf('{h}') # NameError: name 'h' is not defined
If I copy the execprintf function into main.py and does not import from stringhelper.py, it can read h and display 1.
Is it possible to read the h in stringhelper.py?
I need at least exceprintf('a{h}b{i}c{j}d') can run correctly first.
You're making a mistake that's common with beginning programmers, confusing data and code. You write your code before anyone (including yourself) runs a program. The code is not (typically) visible to the application when it's running and shouldn't need to be. When your program is running, a user (yourself or whoever) can enter data and this may change the behaviour of the program, but it never affects the code, nor should the user need to know anything about the code you wrote.
If you need to select a specific value based on some input (file, keyboard, whatever), there are other ways of doing that than picking a variable you know to hold that value by name.
In most cases, using a dictionary is the way to go in Python:
values = {
'a': 'some value',
'b': 'some other value'
}
choice = input('Pick a or b (and hit Enter):')
print('You selected:', values[choice])
Here, the initial values are in the code, but of course you could even load values from a file and the program would still work, without the user ever needing to know about or interact with your code.
Also, running code through exec() is rarely the correct solution. This involves your program running code entered by a user, which could be literally anything if you're not careful, and thus presents major security risks, as well as many opportunities for your code to fail.
The main reason beginning programmers feel the need to reach over and grab exec() or eval() is because they confuse what should remain in the code with what the user has access to - once you fix that, you'll find you rarely need to think about exec() and eval().

How do I call a function in vs code using python?

I'll want to know how to call a function in vs code. I read the answer to similar questions, but they don't work:
def userInput(n):
return n*n
userInput(5)
And appends nothing
def Input(n):
return n*n
And in the terminal:
from file import *
from: can't read /var/mail/file
Can somebody help me?
You are doing everything correctly in the first picture. In order to call a function in python on vs code you first have to define the function, which you did by typing def userInput(n):. If you want to see the result of your function, you should not use return, you should use print instead. Return is a keyword- so when your computer reaches the return keyword it attempts to send that value from one point in your code to another. If you want to see the result of your code, typing print (n) would work better.
Your code should look like this:
def userInput(n):
print (n * n)
userInput(5)
The code would print the result 25
Your terminal is your general way to access your operating system, so you have to tell it that you want it to interpret your Python code first.
If you want to run the file you're typing in, you have to first know the location of that file. When you type ls in your terminal, does the name of your Python file show up? If not, hover over the tab in VSCode (it's close to the top of the editor) and see what path appears. Then in your terminal type cd (short for "change directory") and then the path that you saw, minus the <your filename here>.py bit. Type ls again, and you should see your Python file. Now you can type python <your filename here>.py to run it (provided you have Python installed).
You could also run the IDLE by just typing python in your terminal. This will allow you to write your code line-by-line and immediately evaluate it, but it's easier to write in VSCode and then run it with the method I described before.

PyInstaller: Executable to access user-specified Sourcecode

I'm using pyinstaller to distribute my code as executable within my team as most of them are not coding/scripting people and do not have Python Interpreter installed.
For some advanced usage of my tool, I want to make it possible for the user to implement a small custom function to adjust functionality slightly (for the few experienced people). Hence I want to let them input a python file which defines a function with a fixed name and a string as return.
Is that possible?
I mean the py-file could be drag/dropped for example, and I'd tell them that their user-defined function needs to have a certain name, e.g. "analyze()" - is it now possible to import that from the drag/dropped pythonfile within my PyInstaller Script and use it as this?
I know, it certainly will not be safe/secure and they could do evil things, delete files and so one... But that are things which we don#t care at this point, please no discussions about it. Thanks!
To answer my own question: yes it does actually work to import a module/function from a given path/pythonfile at runtime (that I knew already) even in PyInstaller (that was new for me).
I used this for my Py2.7 program:
f = r'C:\path\to\userdefined\filewithfunction.py'
if os.path.exists(f):
import imp
userdefined = imp.load_source('', f) # Only Python 2.x, for 3.x see: https://stackoverflow.com/a/67692/701049
print userdefined # just a debugging print
userdefined.imported() # here you should use try/catch; or check whether the function with the desired name really exists in the object "userdefined". This is only a small demo as example how to import, so didnt do it here.
filewithfunction.py:
--------------------
def imported():
print 'yes it worked :-)'
As written in the comments of the example code, you'll need a slightly different approach in Python 3.x. See this link: https://stackoverflow.com/a/67692/701049

Trouble importing files in Python

I'm just finding out now that when importing a module, it seems to run through ALL the code, instead of just the one function that I want it to go through. I've been trying to find a way around this, but can't seem to get it. Here is what is happening.
#mainfile.py
from elsewhere import something_else
number = 0
def main():
print('What do you want to do? 1 - something else')
donow = input()
if donow == '1':
something_else()
while 1:
main()
#elsewhere.py
print('I dont know why this prints')
def something_else():
from mainfile import number
print('the variable number is',number)
Now, although this code KIND OF works the way I want it to, the first time when I initiate it, it will go to the main menu twice. For example: I start the program, press one, then it asks me what I want to do again. If I press one again, then it will print "the variable number is 0".
Once I get this working, I would like to be importing a lot of variables back and forth. The only issue is,if I add more import statements to "elsewhere.py" I think it will just initiate the program more and more. If I put "from mainfile import number" on line 1 of "elsewhere.py", I think this raises an error. Are there any workarounds to this? Can I make a different file? What if I made a class to store variables, if that is possible? I'm very new to programming, I would appreciate it if answers are easy to read for beginners. Thank you for the help.
As Jan notes, that's what import does. When you run import, it runs all of the code in the module. You might think: no it doesn't! What about the code inside something_else? That doesn't get run! Right, when the def statement is executed it creates a new function, but it doesn't run it. Basically, it saves the code for later.
The solution is that pretty much all interesting code should be in a function. There are a few cases which make sense to put at the top-level, but if in doubt, put it inside a function. In your particular case, you shouldn't be printing at the top level, if you need to print for some reason, put that into a function and call it when you need it. If you care when something happens, put it in a function.
On a second node, don't import your primary script in other scripts. I.e. if your mainfile.py directly, don't import that in other files. You can but it produces confusing results, and its really best to pretend that it doesn't work.
Don't try to import variables back and forth. Down that path lies only misery. You should only be importing things that don't change. Functions, classes, etc. In any other case, you'll have hard time making it do what you want.
If you want to move variables between places, you have other options:
Pass function arguments
Return values from a function
Use classes
I'll leave it is an exercise to the reader to learn how to do those things.
import executes imported code
import simply takes the Python source file and executes it. This is why it prints, because that instruction is in the code and with import all the instructions get exectued.
To prevent execution of part of imported package/module, you shall use the famous:
if __name__ == "__main__":
print("I do not print with `import`")
Note, that this behaviour is not new in Python 3, it works the same way in Python 2.x too.

How do I execute all the code inside a python file?

How do I execute all the code inside a python file so I can use def's in my current code? I have about 100 scripts that were all written like the script below.
For a simple example, I have a python file called:
D:/bt_test.py
His code looks like this:
def bt_test():
test = 2;
test += addFive(test)
return(test)
def addFive(test):
return(test+5)
Now, I want to from a completely new file, run bt_test()
I've tried doing this:
def openPyFile(script):
execfile(script)
openPyFile('D:/bt_test.py')
bt_test()
But this doesn't work.
I've tried doing this as well:
sys.path.append('D:/')
def openPyFile(script):
name = script.split('/')[-1].split('.')[0]
command = 'from ' + name + ' import *'
exec command
openPyFile('D:/bt_test.py')
bt_test()
Does anyone know why this isn't working?
Here's a link to a quicktime video that will help explain what's happening.
https://dl.dropbox.com/u/1612489/pythonHelp.mp4
You should put those files somewhere on your Python path, and then import them. That's what the import statement is for. BTW: the same directory as your main program is on the Python path, that could be a good place to put them.
# Find and execute bt_test.py, and make a module object of it.
import bt_test
# Use the bt_test function in the bt_test module.
bt_test.bt_test()
The reason that execfile doesn't work is because the functions inside bt_test are limited by the scope of the openPyFile function. One simple test would be to try to run bt_test() from inside openPyFile. Since openPyFile doesn't really do anything other than execfile you could get rid of it altogether, or you could alias execfile
openPyFile=execfile
Note putting the file in your python path and importing it is definitely your best bet -- I only post this answer here to hopefully point out why you're not seeing what you want to see.
In addition to Ned's answer, __import__() might be useful if you don't want the file names hardcoded.
http://docs.python.org/library/functions.html#__import__
Update based on the video.
I don't have access to Maya, but i can try and speculate.
cmds.button(l='print', c='bt_press()') is where the issue seems to lurk. bt_press() is passed as a string object, and whatever way the interpreter uses to resolve that identifier doesn't look in the right namespace.
1) Try passing bt_press() with the module prepended: cmds.button(l='print', c='bt_test.bt_press()')
2) See if you can bind c directly to the function object: cmds.button(l='print', c=bt_press)
Good luck.
>>> from bt_test import bt_test
>>> bt_test()

Categories