从另一个执行python脚本并获取输出

时间:2019-05-20 15:30:31

标签: python

我已经在论坛中搜索过,但是没有找到能解决我问题的任何东西。我有两个简单的脚本P1和P2。 P1应该执行P2并打印其返回值

P1

 import sys
 import subprocess

 sys.path.append('/anaconda2/lib/python2.7/')

 output = subprocess.check_output('python P2.py', shell=True)

 print output

P2

 def foo():
   var1 = 3
   var2 = 6
   return var1 + var2

 foo()

如果我运行P1,则不会收到任何输出,但是如果我运行P2,它将正确打印值9。这是什么问题?谢谢

2 个答案:

答案 0 :(得分:0)

如果要使用其他文件中的功能,则需要#include <stdio.h> #include <string.h> #include <stdlib.h> #define N 10 #define M 10 int text_input(char words[M][N]); int main() { char a[M][N]; text_input(a); return 0; } int text_input(char words[M][N]){ int l=0; /*lines, also how many words the text has */ char a; int i=0; char temp[N]; char endword[10] = {0,0,0,0,0,0,0,0,0,0}; printf("Enter the text. (****TELOS for stoping)"); strcpy(endword, "****TELOS"); while(1){ while(1) { a = getchar(); if (a =='\n'){ if(strcmp(temp, "") == 0){ continue; } else{ break; } } else if (a == ' '){ if(strcmp(temp, "") == 0){ continue; } else{ break; } } else { temp[i++] = a; } } if (strcmp(temp, endword) == 0){ break; } else{ strcpy(words[l++],temp); memset(temp, ' ', strlen(temp)); } } return 0; } (如果它们在同一目录中),然后可以使用import filename

执行它。

编辑:适用于python 3.x

答案 1 :(得分:0)

我怀疑您的IDE欺骗了您,以为P2.py的输出是它没有的。有时,IDE会打印出对调试有用的东西,但不要与脚本输出混淆。您的foo()函数返回9,但P2.py输出 9。

check_output仅返回从子流程打印的内容(请参见the docs)。当前,P2.py不打印任何内容。它仅计算值为9并退出,因此output中的字符串P1.py为空。您永远不会要求它使用foo()的值执行任何操作,因此什么也没做。将foo()中的P2.py替换为print foo(),以实现所需的行为。