2017-07-19 7 views
0

別のスクリプトからpythonスクリプトを呼び出す必要があります。私はexecfile関数の助けを借りてそれをやろうとしています。呼び出し関数の引数として辞書を渡す必要があります。それを行う可能性はありますか?ここでPythonのexecfileに引数を渡す2.7

import subprocess 
from subprocess import Popen 
-------To read the data from xls----- 
ret_lst = T_read("LDW_App05") 

for each in ret_lst: 
    lst.append(each.replace(' ','-')) 
    lst.append(' ') 


result = Popen(['python','LDW_App05.py'] + lst ,stdin = subprocess.PIPE,stdout = subprocess.PIPE).communicate() 
print result 

、上記のコードでは、私は、リストの形式でExcelシートからの入力データを読んでいる、私は、ファイルLDW_App05.pyへの引数としてリストを渡す必要があり

+2

まず、execfileでこれを行う理由を説明してください。 –

+0

ドキュメントについて:https://docs.python.org/2/library/functions.html#execfile 「グローバル」な「ローカル」パラメータがあります。 – Benjamin

+0

入力を読み取るスクリプトを開発しています。いくつかのプロセスを実行し、引数として処理結果を持つ別のpythonスクリプトを呼び出します。私のケースでは動作しなかったos.system、subprocess.popenとsubprocess.callを使用しようとしました – surya

答えて

1

の代わりにSTDIN/STDOUT経由でデータをパイプすることを提案しています。それで、特別なシェルの重要な文字をエスケープし、最大のコマンドラインの長さを超えることを心配する必要はありません。

通常、CL引数ベースのスクリプトとしてあなたがapp.pyのようなものかもしれません:

import sys 

if __name__ == "__main__": # ensure the script is run directly 
    if len(sys.argv) > 1: # if at least one CL argument was provided 
     print("ARG_DATA: {}".format(sys.argv[1])) # print it out... 
    else: 
     print("usage: python {} ARG_DATA".format(__file__)) 

をそれは明確に引数が渡されることを想定し、別のスクリプトから渡された場合、それはそれをプリントアウトし、caller.pyを言う:

import subprocess 

out = subprocess.check_output(["python", "app.py", "foo bar"]) # pass foo bar to the app 
print(out.rstrip()) # print out the response 
# ARG_DATA: foo bar 

しかし、もっと複雑なものを渡したい場合は、dictとしましょう。 dictは階層構造であるため、1行に表示する方法が必要です。あなたはこのような何かにあなたのcaller.pyセットを持っているかもしれないので、ぴったり合う、しかしのは、基本的なJSONに固執せますフォーマットがたくさんあります:

import json 
import subprocess 

data = { # our complex data 
    "user": { 
     "first_name": "foo", 
     "last_name": "bar", 
    } 
} 
serialized = json.dumps(data) # serialize it to JSON 
out = subprocess.check_output(["python", "app.py", serialized]) # pass the serialized data 
print(out.rstrip()) # print out the response 
# ARG_DATA: {"user": {"first_name": "foo", "last_name": "bar"}} 

今あなたがいるという事実を認識するために、あなたのapp.pyを変更した場合再びあなたが得るでしょう、あなたのcaller.pyを実行する場合は、

import json 
import sys 

if __name__ == "__main__": # ensure the script is run directly 
    if len(sys.argv) > 1: 
     data = json.loads(sys.argv[1]) # parse the JSON from the first argument 
     print("First name: {}".format(data["user"]["first_name"])) 
     print("Last name: {}".format(data["user"]["last_name"])) 
    else: 
     print("usage: python {} JSON".format(__file__)) 

:それはあなたがその構造にアクセスするためのPython dictに戻ってそれをデシリアライズすることができます引数としてJSONを受けています

First name: foo 
Last name: bar

これは非常に面倒なことですが、JSONはCLにとって非常に親切ではありません(舞台裏では、Pythonはエスケープして動作させています)。 JSONはこのように渡すことができます。 STDIN/STDOUTバッファを使用して、プロセス間で複雑なデータを渡す方がはるかに優れています。これを行うには、app.pyを修正して、そのSTDINへの入力を待ち、caller.pyにシリアル化されたデータを送信する必要があります。

import json 

if __name__ == "__main__": # ensure the script is run directly 
    try: 
     arg = raw_input() # get input from STDIN (Python 2.x) 
    except NameError: 
     arg = input() # get input from STDIN (Python 3.x) 
    data = json.loads(arg) # parse the JSON from the first argument 
    print("First name: {}".format(data["user"]["first_name"])) # print to STDOUT 
    print("Last name: {}".format(data["user"]["last_name"])) # print to STDOUT 

caller.py

import json 
import subprocess 

data = { # our complex data 
    "user": { 
     "first_name": "foo", 
     "last_name": "bar", 
    } 
} 

# start the process and pipe its STDIN and STDOUT to this process handle: 
proc = subprocess.Popen(["python", "app.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) 
serialized = json.dumps(data) # serialize data to JSON 
out, err = proc.communicate(serialized) # send the serialized data to proc's STDIN 
print(out.rstrip()) # print what was returned on STDOUT 

、あなたはあなたが得るもう一度caller.pyを呼び出す場合:

First name: foo 
Last name: bar

しかし、この時間に制限はありませんので、app.pyはのような単純なことができあなたがapp.pyに渡しているデータサイズであり、シェルエスケープ中に特定のフォーマットがうまくいかないと心配する必要はありません。 tc。「チャネル」を開いたままにしておき、両方のプロセスが双方向で通信できるようにすることもできます(例:this answer)。

関連する問題