(Python) 试图运行一个包含变量的命令提示符命令。

问题描述 投票:0回答:1

基本上,我试图在python中使用os.system运行命令提示符命令来打开一个图像。问题是,我将会把代码和图像传输给一个文件夹内的其他人,所以我希望代码能够工作,不管文件夹放在什么目录下。我写了一些代码,可以找到图片的当前目录,并把它放在一个变量中,但我不知道如何运行命令,如果它的一部分是一个变量,而不是一个长字符串。有什么技巧吗,或者有什么更简单的方法吗?

import os

#Gets/formats directory
def getDirect():

x = list(os.getcwd())

y = ""

for c in x:
    if c == "\\":
        c = "\\\\"

for c in x:
    y = y + c

y = y + "\\imageNameHere.png"

return y

#Prints a valid directory name
print(getDirect())

#Cmd says "The directory name is invalid"
os.system('cmd /k "cd "' + getDirect())
python command-prompt
1个回答
0
投票

使用相对路径[1]

这样一来,只要他把整个文件夹移动,他的文件放在哪里都无所谓。

例如

Folder --> script --> script.py

文件夹 --> image --> image.jpeg。

那么相对路径就是...imageimage.jpeg。

© www.soinside.com 2019 - 2024. All rights reserved.