繁体   English   中英

运行应接受C程序自变量的python脚本

[英]Running python script that should accepts arguments from a C program

我如何从C程序中指定python脚本的参数,在c程序中调用python脚本时必须传递此参数

此C代码能够成功运行python脚本,但是我又如何传递python脚本可以接受的参数呢?

    #include <stdio.h>
    #include <string.h>
    #include <python2.7/Python.h>
    #include <getopt.h>

      int main (int argc, char * argv[])
      {
        char command[50] = "python2.7  /alok/analyze.py";
        system(command);return(0);
      }

从表扬中,我看到了您真正的问题是,如何从2个给定的字符串中制成一个字符串。

您可以做的是:编写一个将2个字符串连接为一个的函数。 为此,您需要获取两个字符串的长度,然后添加此长度(还要为'\\ 0'-Byte添加1并检查溢出),然后使用malloc()为新字符串保留缓冲区空间并复制两者字符串到此缓冲区。

您可以像这样进行操作(不要仅仅使用它,它不是很好的testet,并且错误处理也不是很好):

void die(const char *msg)
  {
    fprintf(stderr,"[ERROR] %s\n",msg);
    exit(EXIT_FAILURE);
  }


char *catString(const char *a, const char *b)
  {
    //calculate the buffer length we need
    size_t lena = strlen(a);
    size_t lenb = strlen(b);
    size_t lenTot = lena+lenb+1; //need 1 extra for the end-of-string '\0'
    if(lenTot<lena) //check for overflow
      {
        die("size_t overflow");
      }
    //reseve memory
    char *buffer = malloc(lenTot);
    if(!buffer) //check if malloc fail
      {
        die("malloc fail");
      }
    strcpy(buffer,a); //copy string a to the buffer
    strcpy(&buffer[lena],b);//copy string b to the buffer
    return buffer;
  }

之后,您可以使用此函数从静态字符串"python2.7 ./myScript "argv[1]创建所需的字符串。

int main(int argc, char **argv)
  {
    //without a argument we should not call the python script
    if(argc<2)
      {
        die("need at least one argument");
      }
    //make one string to call system()
    char *combined = catString("python2.7 ./myScript ",argv[1]);
    printf("DEBUG complete string is '%s'\n",combined);
    int i = system(combined);
    //we must free the buffer after use it or we generate memory leaks
    free(combined);
    if(i<0)
      {
        die("system()-call failed");
      }
    printf("DEBUG returned from system()-call\n");
    return EXIT_SUCCESS;
  }

您需要在"python2.7 ./myScript "额外的空间,而不会得到"python2.7 ./myScriptArgumentToMain"

有了这个,您的调用者就可以执行他喜欢的任何代码,因为我们不会对argv[1]转义,因此,使用yourProgram "argumentToPython ; badProgram argumentToBadProgram"来调用您的程序也会执行badProgram ,这也是您不希望的(在大多数情况下)

暂无
暂无

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

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