Python Forum
Calling python from c++ in visual studio
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Calling python from c++ in visual studio
#1
Hello,

Im trying to call a Python function "fun"in the Sample.py from the c++ console program in visual studio 2019.
The Sample.py works for small one line print function.


But want to use the matplotlib, in the Sample.py file.
I tried the following, but it doesnot work.

Please kindly help. (being newbie to python)

int main()

{

Py_Initialize();

// Create some Python objects that will later be assigned values.


PyObject* pName, * pModule, * pFunc, * pArgs = nullptr, * pValue;

pName = PyUnicode_FromString((char*)"Sample");

pModule = PyImport_Import(pName);

pFunc = PyObject_GetAttrString(pModule, (char*)"fun");

pValue = PyObject_CallObject(pFunc, pArgs);

}
Sample.py was simple function to print.

But now I want to add the following to sample.py
Code:
view sourceprint?
import matplotlib.pyplot as plt

def fun():
# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]
  
# plotting the points 
plt.plot(x, y)
  
# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
  
# giving a title to my graph
plt.title('My first graph!')
  
# function to show the plot
plt.show()
Larz60+ write May-24-2021, 12:41 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Fixed for you this time. Please use bbcode tags on future posts.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Coding in Power BI Visual vjrans 0 271 Jan-31-2024, 07:54 AM
Last Post: vjrans
  python script is hanging while calling a procedure in database prasanthi417 4 501 Jan-17-2024, 02:33 PM
Last Post: deanhystad
  How to set PYTHONPATH in Visual Studio Code? aupres 5 4,123 Aug-15-2023, 03:51 PM
Last Post: snippsat
  how do I open two instances of visual studio code with the same folder? SuchUmami 3 878 Jun-26-2023, 09:40 AM
Last Post: snippsat
  Visual Studio Code NewPi 3 1,043 May-16-2023, 11:13 PM
Last Post: snippsat
  Visual Studio Code venv ibm_db error mesi1000 7 2,784 Nov-13-2022, 12:36 AM
Last Post: snippsat
  debugging help on Visual Studio Code mg24 12 1,993 Oct-02-2022, 12:18 AM
Last Post: mg24
  PyRun_SimpleFile calling multiprocessing Python Class cause endless init loop Xeno 2 1,037 Sep-19-2022, 02:32 AM
Last Post: Xeno
  Problem with importing Python file in Visual Studio Code DXav 7 5,066 Jun-15-2022, 12:54 PM
Last Post: snippsat
  Visual Studio Code Intellisense for Imported Modules Not Working hockinsk 1 2,709 Apr-23-2022, 04:41 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020