473,903 Members | 5,848 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Execute external code and get return value

Hi,
I want to execute an external code, that become from a text file (pe),
call a function inside it and get its return value:

# ext_code.txt

def funct2Call():
return True

# test.py

sourcecode = open("ex_code.t xt").read()
comp_code = compile(sourcec ode, "My_test", "exec")

#do something like this
return_value = comp_code.funct 2Call()

But I can't...

I find this:
http://tinyurl.com/nwbpk

but here, it call from the external code a function inside my code. I
want the opposite!
Is there a solution for do this?

Thanks,
Michele
Sep 29 '06 #1
4 4639
Michele Petrazzo wrote:
I want to execute an external code, that become from a text file (pe),
call a function inside it and get its return value:
namespace = {}
execfile("ext_c ode.txt", namespace)
print namespace["funct2Call "]()

Peter
Sep 29 '06 #2
Michele Petrazzo wrote:

Auto reply:
I find this: http://tinyurl.com/nwbpk
Following this link, here is my solution:
code = """
def funct2Call():
return "It work!"

object.method(f unct2Call)
"""

class Object(object):
def method(self, value):
self._callable = value
def __call__(self):
return self._callable( )

# populate the namespace
namespace = {
"object": Object()
}

# execute the code
exec code in namespace

namespace["object"]()

Michele
Sep 29 '06 #3
Peter Otten wrote:
Michele Petrazzo wrote:
>I want to execute an external code, that become from a text file
(pe), call a function inside it and get its return value:

namespace = {} execfile("ext_c ode.txt", namespace) print
namespace["funct2Call "]()
Sorry, I forgot to say that "ext_code.t xt" isn't a real file, but a text
become from a db, so or I create a temp file where I save the code and
pass its path to execfile, or use my post.
Peter
Thanks,
Michele
Sep 29 '06 #4
Michele Petrazzo wrote:
Following this link, here is my solution:
code = """
def funct2Call():
return "It work!"

object.method(f unct2Call)
"""

class Object(object):
def method(self, value):
self._callable = value
def __call__(self):
return self._callable( )

# populate the namespace
namespace = {
"object": Object()
}

# execute the code
exec code in namespace

namespace["object"]()
Just in case you didn't see it -- the following will work as well:

code = """
def funct2Call():
return "It work!"
"""

namespace = {}
exec code in namespace
namespace["funct2Call "]()

Peter

Sep 29 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
1948
by: Pasquale | last post by:
hello wverybody... i've got a terrible matter with JS my browsers (either IE and NN) load the external scripts uncorrectly...they load the files from the half part of them and not from the beginning, so my scripts don't work giving syntax errors. can you give me a solution?
12
1942
by: John F. | last post by:
Here is my code; Dim psi As New System.Diagnostics.ProcessStartInfo psi.UseShellExecute = True psi.FileName = "C:\WinProg.exe" System.Diagnostics.Process.Start(psi) Have tested WinProg.exe and works., However, when called from .Net, EXE doesn't execute. Any help would be appreciated.
1
2271
by: mb | last post by:
Hi, I picked up this JavaScript code (quiz code) at: http://javascript.internet.com/miscellaneous/multiple-choice-quiz.html and modified it (and may have deleted some line I shouldn't have) so that it looks like this on my web site: http://www.goalseek.net/Scripts/qa_XL_History.htm
4
8489
by: =?Utf-8?B?TEJU?= | last post by:
Good day, I would like to execute an external application from a web form created using ASP.Net. I'm using System.Diagnostics.Process. It works fine if it is notepad.exe but it is not able to execute even a simple VB.Net windows application. No error is being returned. The application just can't be opened (even it is not found inside Task Manager of my web server). Any idea? I'm using IE v 6.0.2900.2180.xpsp_sp2_gdr.050301-1519. My code...
5
3709
by: althafexcel | last post by:
hi everyone Im trying to include an external js in my aspx page under the head tag, it doesn't load or it displays an object expected error whenver the function from the .js is called. Actually for repeated html im using the external js, i mean the TOP, BOTTOM they are repeated in every page, so i include them as functions in the external js and call them. Why it doesn't work?
8
6707
by: M.L. | last post by:
Hello. I created a form using JS validation with the form tag as follows: <form name="form1" action="dynaform.php" method="post" onsubmit="return pvg_sub();"> The js validation script sends alerts when fields are not entered properly and it seems to work, except...when there are no errors, instead executing the php action script, I get a popup dialog box in IE6 asking if I want to download or run the php script. Can anyone tell me
6
2125
by: andrey.vul | last post by:
The error is LNK2001: unresolved external symbol "protected: static bool solver<typename, typename, int, int, int, int, int>::solution" (<vc++ mangled name>) Code (sudoku.cpp): // Sudoku.cpp : Defines the entry point for the console application. // #include <iostream> #include <vector> #include <stdexcept> #include <cstdlib>
1
2432
by: Marty | last post by:
I need to catch exceptions thrown by programs started by the os.system function, as indicated by a non-zero return code (e.g. the mount utility). For example, if I get the following results in a bash shell: $mount test mount: can't find /home/marty/test in /etc/fstab or /etc/mtab then I want to catch the same exception from the corresponding os.system() call, i.e. "os.system('mount test')", but it doesn't work as expected:
1
1390
by: yuan | last post by:
halo.. i face problem when i execute the programming. it appear the error as : 1.obj : error LNK2001: unresolved external symbol "double __cdecl NR::trapzd(double (__cdecl*)(double),double,double,int)" (?trapzd@NR@@YANP6ANN@ZNNH@Z) Debug/1.exe : fatal error LNK1120: 1 unresolved externals Error executing link.exe. can anyone help me ? thanks in advance . below is the programming :
0
10003
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9851
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10882
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10988
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10504
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9692
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7213
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4732
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3327
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.