2016-11-09 6 views
2

次のよう別のpythonスクリプトからpythonスクリプトを呼び出す方法は?次のように私はPythonの "client.py" スクリプトを持っている

import sys 
    import traceback 
    import client_new 
    import subprocess 
    def main(): 
     print "inside client" 
     subprocess.Popen('C:/client_new.py',shell=True) 
     #execfile('client_new.py') 
    if __name__ == "__main__": 
     is_sys_exit = False 
     ret_val = 0 
     try: 
      ret_val = main() 
     except SystemExit: 
      is_sys_exit = True 
     except: 
      if not is_sys_exit: 
       print(traceback.format_exc()) 
       if sys.version_info < (3,0): 
        raw_input("Press return to continue") 
       else: 
        input("Press return to continue") 
       sys.exit(1) 
     if is_sys_exit: 
      print("SystemExit Exception was caught.") 
     sys.exit(ret_val) 

client_new.pyスクリプトは次のとおりです。

ので
import traceback 
    def main(): 
     print "inside client new" 

    if __name__ == "__main__": 
     is_sys_exit = False 
     ret_val = 0 
     try: 
      ret_val = main() 
     except SystemExit: 
      is_sys_exit = True 
     except: 
      if not is_sys_exit: 
       print(traceback.format_exc()) 
       if sys.version_info < (3,0): 
        raw_input("Press return to continue") 
       else: 
        input("Press return to continue") 
       sys.exit(1) 
     if is_sys_exit: 
      print("SystemExit Exception was caught.") 
     sys.exit(ret_val) 

、client.pyから別のスクリプトclient_newがあります。 pyはサブプロセスを使って呼び出されますが、client.pyが実行されるときには、そのデータだけが出力され、client_newの出力は表示されません。したがって、私はclient_new.pyの呼び出しで何が間違っているのか分かりません。私の欠けているものを助けてください。

+3

なぜ単にインポートしてその機能を再利用するのではなく、サブプロセスで他のスクリプトを呼び出すのですか? – jonrsharpe

+0

@jonrsharpe実際に私はそれを行う方法はわかりません – Learner

答えて

1

彼らは両方が同じディレクトリにある(またはPythonが探しているディレクトリにあります(私はPYTHONPATHと呼ばれると思います))、それは比較的簡単です。 Pythonファイルをインポートするには、.pyを削除してインポートします。したがって、次のコードが必要です。

import client_new 
#Write rest of the code here 
client_new.run_function() 

client_newでコードを少し変更して機能させる必要があります。

+0

http://stackoverflow.com/questions/2349991/python-how-to-import-other-python-filesがさらに役立つかもしれないことを教えてください。 –

1

client_new.pyモジュールを管理している場合は、A. N. Otherの回答を強くお勧めします。

def main(): 
    print 'inside client' 
    proc = subprocess.Popen('C:/client_new.py', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
    stdout = proc.stdout.read() 
    stderr = proc.stdout.read() 
    print 'Got output from client_new:\n' + stdout 
    if stderr: 
     print 'Got error output from client_new:\n' + stderr 

サイドノート:そうしない場合は、にclient.pyであなたのmain()機能を変更することを避けることができる場合subrocessでshell=Trueを使用しないでください。 Use subprocess.Popen(['client_new.py'], ...)

関連する問題