2016-02-28 272 views
0

我正在構建一個可以自動執行系統管理員類型任務的python實用程序。部分工具涉及編寫腳本,然後使用python界面中的powershell調用它們。這種代碼的一個例子是這樣的:Python - os.system調用中的相對路徑

def remote_ps_session(): 
    target = raw_input("Enter your target hostname: ") 
    print "Creating target.ps1 file to establish connection" 
    pstarget = open("pstarget.ps1", "w") 
    pstarget.write("$target = New-Pssession " + target + "\n") 
    pstarget.write("Enter-PSSession $target" + "\n") 
    pstarget.close() 
    print "File created. Initiating Connection to remote host..." 
    os.system("powershell -noexit -ExecutionPolicy Unrestricted " + "C:\path\to\my\file\pstarget.ps1") 

我希望做兩件事情,我認爲可以用同樣的方法來回答,我只是還沒有搞清楚什麼是最好的(進口VS變量VS初始設置定義等)

爲了簡單起見,我們會說的效用是在C:\實用程序和PowerShell函數是在一個文件夾的功能更深一層:C:\程序\功能

我想能夠爲1)腳本(被寫入的文件)保存到的位置指定位置,然後2)在執行os.system調用時指向該位置。我希望這可以在大多數/任何現代Windows系統上運行。

我對可能性的想法是:

  1. 當腳本啓動獲取當前目錄中,並且保存爲一個變量,如果我需要回到一個目錄中採取的變量,並在最後\刪除一切,等等。看起來並不理想。
  2. 第一次啓動系統位置的文件提示以輸入變量。例如讓它提示'你想要你的日誌文件在哪裏?' '你想要你的輸出文件在哪裏?' '你想在哪裏生成腳本?'這些可以被稱爲變量,但如果它們移動了文件夾就會中斷,並且可能不容易爲用戶「修復」。
  3. 我想有一種方法可以引用當前目錄並導航到.. \ parallel文件夾到我正在執行的目錄。 .... \ 2文件夾,但也似乎可能是混亂。我還沒有看到管理這個標準/最佳實踐是什麼。

編輯:根據一些評論我認爲__file__可能是開始尋找的地方。我將深入研究這一些,但任何例子(例如:__file__/subfoldername或任何使用會很酷。

+0

'os.system'使用'cmd.exe'(除非你改變%comspec%),但你有powershell腳本。你爲什麼用這個而不是'subprocess'?你的例子有一個'''在其中的路徑 - 確保你使用一個原始字符串,或者反斜槓,或者使用正斜槓作爲目錄分隔符。 – cdarke

+0

@cdarke我只是最近才發現了關於子進程的問題,並且當我希望將輸出返回到python會話中時,它已經合併了它。現在,我的大多數模塊(可惜)都使用cmd.exe來爲腳本調用powershell,如上所述。令人驚訝的是,上面的路徑確實有效(不是確切的路徑,而是那種格式)。但我會將它們切換爲正斜槓。謝謝(你的)信息。 – Abraxas

+1

'subprocess.check_call'適用於不需要捕獲輸出的情況。 –

回答

1

Python有一個專用於路徑操作os.path,所以任何時候你需要文件系統路徑操作採取。一看它

至於你的具體問題,運行下面的例子,就看你如何使用此lib中的功能:

test.py

import os 
# These two should basicly be the same, 
# but `realpath` resolves symlinks 
this_file_absolute_path = os.path.abspath(__file__) 
this_file_absolute_path1 = os.path.realpath(__file__) 
print(this_file_absolute_path) 
print(this_file_absolute_path1) 
this_files_directory_absolute_path = os.path.dirname(this_file_absolute_path) 
print(this_files_directory_absolute_path) 
other_script_file_relative_path = "functions/some.ps" 
print(other_script_file_relative_path) 
other_script_file_absolute_path = os.path.join(this_files_directory_absolute_path, 
               other_script_file_relative_path) 
print(other_script_file_absolute_path) 
print("powershell -noexit -ExecutionPolicy Unrestricted %s" % 
     other_script_file_absolute_path) 

你應該得到輸出與此類似:

/proj/test_folder/test.py 
/home/user/projects/test_folder/test.py 
/proj/test_folder 
functions/some.ps 
/proj/test_folder/functions/some.ps 
powershell -noexit -ExecutionPolicy Unrestricted /proj/test_folder/functions/some.ps