簡體   English   中英

Python subprocess.Popen() 未運行命令

[英]Python subprocess.Popen() not running command

我正在嘗試使用subprocess.Popen()在我的腳本中運行命令。 代碼是:

output = Popen(["hrun DAR_MeasLogDump " + log_file_name], stdout=subprocess.PIPE, stderr = subprocess.PIPE, executable="/bin/csh", cwd=cwdir, encoding='utf-8')

當我打印 output 時,它打印出創建的 shell output 而不是列表中的實際命令。 我嘗試擺脫executable='/bin/csh' ,但 Popen 甚至無法運行。

我也嘗試使用subprocess.communicate() ,但它也沒有用。 我還會得到 shell output 而不是實際的命令運行。

由於安全問題,我想完全避免使用shell=True

編輯:在許多不同的嘗試中,“hrun”沒有被識別。 “hrun”是被調用的 Pearl 腳本,DAR_MeasLogDump 是操作,log_file_name 是腳本將調用其操作的文件。 是否需要進行任何類型的設置或配置才能識別“hrun”?

嘗試:

output = Popen(["-c", "hrun DAR_MeasLogDump " +log_file_name], stdout=subprocess.PIPE, stderr = subprocess.PIPE, executable="/bin/csh", cwd=cwdir, encoding='utf-8')

csh期望-c "full command here" 沒有-c我認為它只是嘗試將其作為文件打開。

在這里指定一個奇數外殼程序和一個顯式的cwd似乎完全cwdir (假設cwdir已定義到當前目錄)。

如果subprocess的第一個參數是列表, 則不涉及任何外殼程序。

result = subprocess.run(["hrun", "DAR_MeasLogDump", log_file_name],
    stdout=subprocess.PIPE, stderr = subprocess.PIPE,
    universal_newlines=True, check=True)
output = result.stdout

如果您需要在舊版本的Python下run ,則可以使用check_output而不是run

通常,除非需要執行高級包裝函數無法執行的操作,否則通常要避免使用Popen

您正在創建subprocess.Popen的實例,但不執行它。

你應該試試:

p = Popen(["hrun", "DAR_MeasLogDump ", log_file_name], stdout=subprocess.PIPE, stderr = subprocess.PIPE, cwd=cwdir, encoding='utf-8')

out, err = p.communicate()  # This will get you output

如果不使用shell=True ,則應將Args作為序列傳遞,然后不要求使用executable

請注意,如果您不使用Popen高級功能,則文檔建議使用subprocess.run

from subprocess import run

p = run(["hrun", "DAR_MeasLogDump ", log_file_name], capture_output=True, cwd=cwdir, encoding='utf-8')

out, err = p.communicate()  # This will get you output

這適用於cat示例:

import subprocess

log_file_name='-123.txt'

output = subprocess.Popen(['cat', 'DAR_MeasLogDump' + log_file_name], 
                                stdout=subprocess.PIPE, 
                                stderr=subprocess.STDOUT)
stdout, stderr = output.communicate()
print (stdout)
print (stderr)

我認為您只需要更改您的' hrun '命令

我認為問題在於 Popen 需要命令的每個部分(命令 + 選項)的列表,子進程內的 Popen 文檔有一個示例。 因此,要使腳本中的該行起作用,您需要像這樣編寫它:

output = Popen(["/bin/csh", "hrun", "DAR_MeasLogDump", log_file_name], stdout=subprocess.PIPE, stderr = subprocess.PIPE)

我已經刪除了可執行參數,但我想它也可以這樣工作。

這似乎與我在項目開始時遇到的問題相同:您已嘗試使用 windows "environment variables" It turns out that when entering the CMD or powershell it does not recognize perl, java, etc. unless you go to the folder where the.exe.py.java, etc. is located and enter the cmd, where the java.exe, python.py等是。

在我的 ADB 項目中,一旦我添加了我的環境變量,我就不再需要 go 到 .exe.py 或 adb 代碼所在的文件夾。

現在你可以打開一個 CMD,它會執行任何來自你的 perl 的命令,所以使用 powershell 的解釋器會找到並識別這個命令。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM