Python如何存储"\&引用;在arrey中使用subprocess.call bash命令
我有一个python程序,它创建一个bash命令,然后在subprocess.call(command)中使用它 我想给它发送一个带有空格的文件位置Python如何存储"\&引用;在arrey中使用subprocess.call bash命令,python,bash,subprocess,Python,Bash,Subprocess,我有一个python程序,它创建一个bash命令,然后在subprocess.call(command)中使用它 我想给它发送一个带有空格的文件位置 import subprocess command = ["mkdir","/home/matt/Desktop/this"] command[1] += "\\ is" subprocess.call(command) 但当它被子进程使用时,它将成为一个名为 这是 这是完整的代码 import pyxhook import subproces
import subprocess
command = ["mkdir","/home/matt/Desktop/this"]
command[1] += "\\ is"
subprocess.call(command)
但当它被子进程使用时,它将成为一个名为
这是
这是完整的代码
import pyxhook
import subprocess
command = [""]
isActive = False
element = 0
isSpace = False
def OnKeyPress(event):
global command
global isActive
global element
global isSpace
if event.Ascii == 96:
if isActive == False:
isActive = True
elif isActive == True:
subprocess.call(command)
command = [""]
element = 0
isActive = False
elif isActive == True:
if event.Ascii == 32:
if isSpace == False:
command.append("")
element += 1
else:
command[element] += " "
isSpace = False
elif event.Key == "BackSpace":
command[element] = command[element][:-1]
elif event.Key == "slash":
command[element] += "/"
elif event.Key == "Shift_L" :
command = command
elif event.Key =="Shift_R":
command = command
elif event.Key == "backslash":
isSpace = True
command[element] += "\\"
else:
command[element] += (event.Key)
#instantiate HookManager class
new_hook=pyxhook.HookManager()
#listen to all keystrokes
new_hook.KeyDown=OnKeyPress
#hook the keyboard
new_hook.HookKeyboard()
#start the session
new_hook.start()
请注意您的命令列表以及如何添加内容:
$ python
Python 2.7.10 (default, Feb 7 2017, 00:08:15)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> command = ["mkdir", "/home/matt/Desktop/this"]
>>> command[0] += "\\ is"
>>> command
['mkdir\\ is', '/home/matt/Desktop/this']
>>> command = ["mkdir", "/home/matt/Desktop/this"]
>>> command[-1]
'/home/matt/Desktop/this'
>>> command[-1] += " is"
>>> command
['mkdir', '/home/matt/Desktop/this is']
>>> subprocess.call(command)
0
>>> import glob
>>> glob.glob("/home/matt/Desktop/th*")
['/home/matt/Desktop/this is']
>>>
保持简单:
path = "/home/matt/Desktop/this"
path += " is"
os.makedirs(path, exist_ok=True)
如果您的Python版本早于3.2,请删除exist\u ok=True
谢谢您的帮助
import subprocess
command = ["mkdir","/home/matt/Desktop/this"]
command[1] += " is"
subprocess.call(command)
使用子流程时不需要使用\它将运行。字符串将隐式转换为字符列表。然后它将与列表一起扩展。我编辑了我的帖子以反映这些问题,并发布了我的完整代码您不需要转义任何内容,因为shell没有处理
command
。字符串值作为一个参数直接传递给execve
(或exec
s中的一个)。