简体   繁体   中英

How to run a Python executable(.py) within a C program (for example by using execvp)?

I have this piece of code for running a Python program and I expect my shell to run a python program when I enter something like the following : mysh> hello.py

But hello.py is not passed to /usr/bin/python in execvp and I need help figuring out how to correctly pass arguments to execvp.

 if (pid==0)   // child process         
     {

      if (py_flag==1)
         execvp("/usr/bin/python",argv);
      else
       {

        execvp(argv[0],argv);
        perror("error");
       }
     }

And here's the result I am receiving:

./basic_shell 
mysh> hello.py
I am a python program
Python 2.6.6 (r266:84292, May 27 2013, 05:35:12) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 

While I expect to receive a result like this:

$ python hello.py 
sys.argv[0] = hello.py

Please let me know how can this be fixed.

I changed my code to this and now it is working as expected:

  if (pid==0)   //child process 
     {

      if (py_flag==1)
         {
           char *new_argv[2];
           new_argv[0]="/usr/bin/python";
           new_argv[1]=argv[0];
           new_argv[2]=0;
           //execvp("/usr/bin/python",argv);
           execvp(new_argv[0],new_argv);
         }
      else
       {

        execvp(argv[0],argv);
        perror("error");
       }
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM