【发布时间】:2016-12-11 05:30:29
【问题描述】:
我正在尝试在 Python 中创建一个翻译器类型的程序(这是 2.7,如果这很重要的话)。我想接收用户输入,翻译它,然后将他们的输出打印到屏幕上。那部分并不难,但我也想将它导出到文本文件。为此,我使用 Powershell 和 subprocess 模块。 Powershell 脚本非常短,它所做的只是要求用户将 Python 翻译复制并粘贴到输入中。然后它调用 New-Item 来创建一个文件,并为其提供 value 选项作为 Python 翻译。
Python 代码:
def translator:
inquiry = raw_input("Leetspeak trans query: ") #Enter query
inquiry = inquiry.lower() #Change all to lowercase, so that everything gets translated
newPrint1 = "" #The new string that gets returned to them at the end
level = raw_input("What type of 1337 do you want? 1 for basic, 2 for intermediate, \
3 for intermediate-advanced, and 4 for ultimate.")
if level == "1":
from b4s1c_l33t import leetkey
elif level == "2":
from In73rm3d1473_1337 import leetkey
elif level == "3":
from In7_4DV import leetkey
from In7_4DV import combokey
elif level == "4":
from U17IM473_1337 import leetkey
from U17IM473_1337 import combokey
for char in inquiry:
if char in leetkey:
newPrint1 += leetkey[char]
else:
newPrint1 += char #Checks to see if the char is in the single-char list, then appends it accordingly
if int(level) >= 3:
for item in combokey:
if item in newPrint1:
newPrint1 = newPrint1.replace(item, combokey[item])
print newPrint1 #Print answer
question = raw_input(r"Do you want to translate some more? Type Y or N ") #Asks if they want to do more
question = question.lower() #Changes it to lowercase, for sending through the if loop
if question == "y" or question == "Y":
translator() #If answer is yes, program calls the entire function again
elif question != "y" and question != "n" and question != "Y" and question != "N":
print "I didn't quite catch that."
ps = raw_input("Would you like to export your leetness to a file? Type Y or N ")
if ps == "Y" or ps == "y":
import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./1337Export.ps1\";", "&export"])
else:
print r"0|<. 600|)|3`/3!"
translator() #calls the function once
Powershell 脚本:
Function export(){
$param = Read-Host("Copy-paste the translation from above here! ")
New-Item C:\Scripts\1337\1337ness.txt -type file -value $param
}
但我也知道,在我向其中添加 Powershell 之前,该脚本一直运行良好,因此问题在于我对子进程模块的使用或 Powershell 脚本本身。我是一个使用 Powershell 的中级初学者,因此将不胜感激任何帮助。或者,如果有一种方法可以创建新文件并将数据写入 Python 本身,那将不胜感激。
谢谢, 前言
注意:在 Python 脚本中,leetkey 和 combokey 位于根据变量 level 的值导入的单独文件中.
更新:我查看了页面here,Python 脚本中的subprocess 代码就是我在该页面中找到的。它没有用,而是抛出了一个错误,指出 export 函数不存在,它显然确实存在......在 Powershell 中。再次感谢!
【问题讨论】:
-
这能回答你的问题吗? Run PowerShell function from Python script
标签: python-2.7 powershell subprocess