Python如何在arrey中存储“\”以用于子流程调用bash命令

2024-04-19 06:44:29 发布

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

我有一个python程序,它创建一个bash命令,然后在中使用它子流程调用(命令)

我想给它发一个有空格的文件位置。你知道吗

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()

Tags: keyimporteventfalsetruenewifelement
3条回答

谢谢你的帮助

import subprocess
command = ["mkdir","/home/matt/Desktop/this"]
command[1] +=  " is"
subprocess.call(command)

使用子流程时,不需要使用\

保持简单:

path = "/home/matt/Desktop/this"
path += " is"
os.makedirs(path, exist_ok=True)

如果您的Python早于3.2,请删除exist_ok=True。你知道吗

请注意您的命令列表以及如何附加内容:

$ 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']
>>>

相关问题 更多 >