从python内部运行原始powershell代码时出现问题

2024-09-19 23:34:44 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下脚本:

import os,sys,subprocess
mypwr_shell_code = '''
function test_args()
{
  echo "heres arg 0: $($args[0])"
  echo "heres arg 1: $($args[1])"
  echo "heres arg 2: $($args[2])"
  echo "heres arg 3: $($args[3])"
  echo "heres arg 4: $($args[4])"
  echo "heres arg 5: $($args[5])"
  echo "heres arg 6: $($args[6])"
  echo "heres arg 7: $($args[7])"
  echo "heres arg 8: $($args[8])"
  echo "heres arg 9: $($args[9])"
  echo "heres arg 10: $($args[10])"
}

test_args $args

"================================================"
date
"================================================"
pwd
"================================================"
dir getprocesses.ps1
"================================================"
'''

如何在python中运行此代码,而不必将代码写入磁盘

我试过这个:

results = subprocess.Popen(["powershell.exe", "-NonInteractive", "-EncodedCommand", mypwr_shell_code], stdout=subprocess.PIPE)
print(results)

这导致了以下错误:

Traceback (most recent call last):
  File "C:\Users\J\solid.py", line 3704, in <module>
    process = subprocess.Popen(["powershell.exe", "-NonInteractive", "-EncodedCommand", mypwr_shell_code], stdout=subprocess.PIPE)
  File "C:\Python27\lib\subprocess.py", line 710, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
    startupinfo)
WindowsError: [Error 206] The filename or extension is too long

我还尝试:

print ( os.system('iex "%s"' % (mypwr_shell_code) ) )

这导致了-1

注意,mypwr_shell_code中的代码可能比这里显示的要复杂得多

我这里要问的是如何从python中运行powershell代码(存储在变量中)

请告知


Tags: 代码inpyechooslineargargs