I have this script:
from myhelperfunctions import *
# parse arguments
args = docopt(__doc__, version='mainprog 1.0')
myhelper1(args)
...
This is a script someone else maintains and I have no control over, so i cant modify it. The script structure looks like
/opt/app-to-import/{main.py, myhelperfunctions.py}
I want to run this code in another program in my home directory, but don't want to start a new process. so I tried exec() and imp.load_source() to load and run it inside the same process. But every time it complains saying no module named myhelperfunctions. What is the right way to do this? I am using python2.7.
Related
I have couple questions regarding running code from multiple files from one .py file
When I import the Files with
from [subfolder] import [First scriptname - without .py]
from [subfolder] import [Second scriptname - without .py]
the scripts start running instantly, like if my scripts have a print code it would look like this after running the combined-scripts file
print("Hi Im Script One")
print("Hi Im Script Two")
now I could put them in functions and run the functions but my files also have some variables that are not inside functions, the question I have is if there is a way to not start the script automatically after import?
Also what happens with variables inside these scripts, are they usable throughout the combined file or do i need to state them with something like "global"?
is there a way to not start the script automaticly after import?
This is what python's if __name__ == "__main__": is for.
Anything outside that (imports, etc.) will be run when the .py file is imported.
what happens with variables inside these scripts, are they usable troughout the combined file or do i need to state them with something like "global"?
They may be best put inside a class, or you can also (not sure how Pythonic/not this is):
from [FirstScriptName_without_.py] import [className_a], [functionName_b], [varName_c]
I want to make my own programming language based on python which will provide additional features that python wasn't provide, for example to make multiline anonymous function with custom syntax. I want my programming language is so simple to be used, just import my script, then I read the script file which is imported my script, then process it's code and stop anymore execution of the script which called my script to prevent error on syntax...
Let say there are 2 py file, main.py and MyLanguage.py
The main.py imported MyLanguage.py
Then how to get the main.py file from MyLanguage.py if main.py can be another name(Dynamic Name)?
Additional information:
I using python 3.4.4 on Windows 7
Like Colonder, I believe the project you have in mind is far more difficult than you imagine.
But, to get you started, here is how to get the main.py file from inside MyLanguage.py. If your importing module looks like this
# main.py
import MyLanguage
if __name__ == "__main__":
print("Hello world from main.py")
and the module it is importing looks like this, in Python 3:
#MyLanguage.py
import inspect
def caller_discoverer():
print('Importing file is', inspect.stack()[-1].filename)
caller_discoverer()
or (edit) like this, in Python 2:
#MyLanguage.py
import inspect
def caller_discoverer():
print 'Importing file is', inspect.stack()[-1][1]
caller_discoverer()
then the output you will get when you run main.py is
Importing file is E:/..blahblahblah../StackOverflow-3.6/48034902/main.py
Hello world from main.py
I believe this answers the question you asked, though I don't think it goes very far towards achieving what you want. The reason for my scepticism is simple: the import statement expects a file containing valid Python, and if you want to import a file with your own non-Python syntax, then you are going to have to do some very clever stuff with import hooks. Without that, your program will simply fail at the import statement with a syntax error.
Best of luck.
I'm sure this is very simple but I've been unable to get it working correctly. I need to have my main python script call another python script and pass variables from the original script to the script that I've called
So for a simplistic example my first script is,
first.py
x = 5
import second
and my second script is,
second.py
print x
and I would expect it to print x but I get
NameError: name 'x' is not defined
I'm not sure if import is right way to achieve this, but if someone could shed light on it in a simple way that would be great!
thanks,
EDIT
After reading the comments I thought I would expand on my question. Aswin Murugesh answer fixes the import problem I was having, however the solution does not have the desired outcome as I can not seem to pass items in a list this way.
In first.py I have a list which I process as follows
for insert, (list) in enumerate(list, start =1):
'call second.py passing current list item'
I wanted to pass each item in the list to a second python file for further processing (web scraping), I didn't want to do this in first.py as this is meant to be the main 'scan' program which then calls other programs. I hope this now make more sense.
Thanks for the comments thus far.
When you call a script, the calling script can access the namespace of the called script. (In your case, first can access the namespace of second.) However, what you are asking for is the other way around. Your variable is defined in the calling script, and you want the called script to access the caller's namespace.
An answer is already stated in this SO post, in the question itself:
Access namespace of calling module
But I will just explain it here in your context.
To get what you want in your case, start off the called script with the following line:
from __main__ import *
This allows it to access the namespace (all variables and functions) of the caller script.
So now your calling script is, as before:
x=5
import second
and the called script is:
from __main__ import *
print x
This should work fine.
use the following script:
first.py:
x=5
second.py
import first
print first.x
this will print the x value. Always imported script data should be referenced with the script name, like in first.x
To avoid namespace pollution, import the variables you want individually: from __main__ import x, and so on. Otherwise you'll end up with naming conflicts you weren't aware of.
Try use exec
Python3.5:
first.py
x=5
exec(open('second.py').read())
second.py
print(x)
You can also pass x by using:
x=5
myVars = {'x':x}
exec(open('second.py').read(), myVars)
Not sure if this is a good way.
Finally,
I created a package for Python to solve this problem.
Install Guli from PIP.
$ pip install guli
Guli doesn't require installing any additional PIP package.
With the package you can
Guli can be used to pass between different Python scripts, between many processes or at the same script.
pass variables between main Process and another (Multiprocess) Process.
Pass variables between different Python scripts.
Pass variables between 'Main Process' and another (Multiprocess) Process.
Use variables at the same script.
Create / Delete / Edit - GuliVariables.
Example
import guli
import multiprocessing
string = guli.GuliVariable("hello").get()
print(string) # returns empty string ""
def my_function():
''' change the value from another process '''
guli.GuliVariable("hello").setValue(4)
multiprocessing.Process(target=my_function).start()
import time
time.sleep(0.01) # delay after process to catch the update
string = guli.GuliVariable("hello").get()
print(string) # returns "success!!!"
Hope I solved the problem for many people!
I am trying to write a WLST script.
As I found that I always repeat doing similar setup, I tried to make some util functions to ease my script writing.
Later when I tried to pull those functions to an external .py as a module, I failed to do so:
assume I have a main script (domain_config.py), and the util function script (wlst_util.py)
Here is what I put in domain_config.py:
import wlst_util import *
loadProperties('domain.properties')
....
create_jms_conn_factory(....);
First it complains for my delcaration in the wlst_util.py for the method:
create_jms_conn_factory(...., is_xa=False)
it complains "NameError: False".
ok, then I remove the default param, then it complains for those cd() function (provided by WLST).
Then I tried to do "from wl import *" in wlst_util.py, the script failed at loadProperties line (NullPointerException).
I tried to put the import after loadProperties, then the cmo variable in my main script become None...
What is the right way I should do just for pulling those util function to a separate file?..
Thanks
I am trying to figure out how to use Python in Maya. I wanted to create a shelf in Maya and when I click that shelf, it will execute a file containing python code.
First thing, I figured out that we can't simply source python script. I followed this tutorial, so now I have a function psource(). In my shelf, I can just call psource("myPythonScript")
My problem is I have to somehow register psource() when Maya first loaded.
Any idea how to do this?
I suggest that you import the Python module with your button before calling the function. Assuming your script is in maya/scripts/tep.py, your button would do the following:
import tep
tep.psource()
If you wanted to modify the script and keep running the fresh version every time you hit the button, do this:
import tep
reload(tep)
tep.psource()
And if you want your module to load on Maya startup, create a file called userSetup.py in your maya/scripts directory and have it do this:
import tep
Then, your button can simply just:
tep.psource()
Or...
reload(tep)
tep.psource()
As part of the Maya startup sequence, it'll execute a file called userSetup.py for you. Within that file you can stick in standard python code to set up your environment, etc.
docs: http://download.autodesk.com/global/docs/maya2013/en_us/index.html?url=files/Python_Python_in_Maya.htm,topicNumber=d30e725143
That's the 2013 docco, but it's valid in 2011 and 2012 too. I expect it to be correct going back further as well, but I'm not running anything older here
For an example btw, my userSetup.py file looks like this:
import sys
# import a separate pyscript dir - we keep the standard scriptdir for MEL
sys.path.append(r'C:/Users/tanantish/Documents/maya/2012-x64/pyscripts')
# odds on i'm going to want PyMEL loaded by default
# and we are going to try distinguish it from the old maya.cmds
# since the two since they're similar, but not the same.
# from pymel.core import *
import pymel.core as pm
# and we might as well get maya.cmds in for testing..
import maya.cmds as mc
# import local toolpack
import tantools
(edited to caps out userSetup.py as per #jdi's comment)
Which version of Maya are you running? If later than 8.5, Maya has python built in. Any python scripts you put in your local Maya script directory gets automatically sourced. You can inside the script editor source and run python scripts.
To automatically run:
Create a userSetup.mel file in myDocs\maya\mayaVersion\scripts
Inside the userSetup, use this syntax to import and run scripts:
python("from package import module");
python("module.method(\"passedVar1\", \"passedVar2\")");
Hope that helps
P.S Same syntax applies for shelf buttons. Just have to make sure that you have your python path set for Maya so that your code can be found. The local script directory is already included.....
I like to use
exec(open('c:\whatever\whatever\scriptname.py'))
See if that works for you! :)