2015-12-24 191 views
0

我正在使用python 3,我需要一個腳本來調用另一個shell,並且在不傳遞參數的情況下運行它,我使用的是mac os x,但是我需要它是跨平臺的。從另一個python腳本執行python腳本打開另一個shell

我試着用

os.system('script2.py') 
    subprocess.Popen('script2.py',  shell=true) 
    os.execl(sys.executable, "python3", 'script2.py') 

但他們沒有做到我需要什麼。

我用的是第二個腳本獲得輸入,而第一個處理輸出...

編輯

這是我的第二個腳本代碼:

import sys 
import os 
import datetime 

os.remove('Logs/consoleLog.txt') 
try: 
    os.remove('Temp/commands.txt') 
except: 
    ... 

stopSim = False 

command = '' 

okFile = open('ok.txt', 'w') 
okFile.write('True') 
consoleLog = open('Logs/consoleLog.txt', 'w') 

okFile.close() 

while not stopSim: 

    try: 
     sysTime = datetime.datetime.now() 
     stringT = str(sysTime) 
     split1 = stringT.split(" ") 
     split2 = split1[0].split("-") 
     split3 = split1[1].split(":") 

     for i in range(3): 
      split2.append(split3[i]) 

     timeString = "{0}-{1}-{2} {3}:{4}".format(split2[2], split2[1], split2[0], split2[3], split2[4]) 
    except: 
     timestring = "Time" 

    commandFile = open('Temp/commands.txt', 'w') 

    command = input(timeString + ": ") 
    command = command.lower() 

    consoleLog.write(timeString + ': ' + command + "\n") 
    commandFile.write(command) 

    commandFile.close() 
    if command == 'stop simulation' or command == 'stop sim': 
     stopSim = True 

consoleLog.close() 
os.remove('Temp/commands.txt') 

這是我打電話的地方,另一個腳本在腳本1中的操作:

#Open console 

while not consoleOpent: 
    try: 
     okFile = open('ok.txt', 'r') 
     c = okFile.read() 
     if c == 'True': 
      consoleOpent = True 
    except: 
     ... 

S orry的長期問題... 任何改善代碼的建議是受歡迎的。

回答

0

也許最簡單的解決方案是讓內容你第二個腳本中的第一個腳本功能,並執行它作爲一個multiprocessingProcess。請注意,您可以使用e.q. multiprocessing.Pipemultiprocessing.Queue在不同進程之間交換數據。您也可以通過multiprocessing.sharedctypes共享值和數組。

+0

@ Enderlike61是的,這基本上它做什麼。我已經添加了一個鏈接到文檔。 –

0

這將取決於平臺。這裏的Mac OS X的解決方案

與此內容創建新文件run_script2

/full/path/to/python /full/path/to/script2.py 

使其可執行:chmod +x run_script2

運行從Python來:

os.system('open -a Terminal run_script2') 

或者你可以使用:subprocess.call

subprocess.call(['open -a Terminal run_script2'], shell=True) 

在Windows中,你可以做(​​未經測試)類似的東西:

os.system('start cmd /D /C "python script2.py && pause"') 
+0

謝謝,但我的成就是讓它跨平臺... – Enderlike61

相關問題