简体   繁体   English

如何在C程序中运行Python可执行文件(.py)(例如,使用execvp)?

[英]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 我有这段用于运行Python程序的代码,当我输入以下内容时,我希望我的shell运行python程序: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. 但是hello.py没有在execvp中传递给/ usr / bin / python,我需要帮助弄清楚如何正确地将参数传递给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");
       }
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使python程序“ .py”可执行? - How to make python program “.py” executable? 默认情况下如何在python 3下运行.py可执行文件? - How to run .py executable under python 3 by default? 如何使用多线程在python中从另一个程序(比如说“c.py”)并行运行两个独立的程序(比如“a.py”和“b.py”)? - how to run two seperate independent programs(say “a.py” and “b.py”) parallely from another program(say “c.py”) in python using multi-threading? 如何使用Twisted Python运行C程序并获取程序输出 - How to run a C program and get output of the program using Twisted Python 当以可执行文件./xxx.py运行程序时,设置默认的python版本 - set default python version when run the program as executable ./xxx.py - on linux 如何使用 Python 运行外部可执行文件? - How to run external executable using Python? 如何使用python使可执行文件在后台运行? - How to make executable run in background using python? 如何使用python运行几个可执行文件? - how to run several executable using python? 使用py2exe,如何使用python和tkinter创建可执行文件? - Using py2exe, how to create an executable usng python and tkinter? 如何制作可执行的shell脚本来运行我的.py程序并输入文件 - How to make an executable shell script to run my .py program and input a file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM