【问题标题】:Running python script that should accepts arguments from a C program运行应该接受来自 C 程序的参数的 python 脚本
【发布时间】:2017-08-18 06:35:18
【问题描述】:

如何从 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);
      }

【问题讨论】:

  • 只是在/alok/analyze.py 之后添加参数不起作用?
  • 我认为您不需要标题Python.h,您不使用任何python函数,您只需使用字符串调用system(),然后只需使用fork()-exec()-wait () 也与 Python 无关,你的程序不需要了解 Python。
  • 那么您的错误不在此调用中,system() 只会运行execl("/bin/sh","-c",command,NULL);
  • 您知道您通过此调用只需将字符串"-dargv[1]" 传递给它吗?如果要使用 argv 参数,则必须将其复制为 system() 的单个字符串,或使用 fork()exec() 函数之一。
  • 你不能只忽略双引号。您将需要保留足够的缓冲区空间(您必须确保此缓冲区大于两个字符串的总和,或者如果它太长则中止它)并将两个字符串复制到此缓冲区中。这样您就有一个字符串,其中包含 system() 的完整参数

标签: python c python-2.7 arguments


【解决方案1】:

从表扬中,我看到你真正的问题是,如何从 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,这也是你不想要的(在大多数情况下)

【讨论】:

    猜你喜欢
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 2015-03-15
    相关资源
    最近更新 更多