Скрипт в Python с использованием подпроцесса не работает - PullRequest
1 голос
/ 04 апреля 2020

Я работаю над сценарием, в котором вы вводите число, и сценарий создает папку для вас и открывает проводник в папке. Но у меня с этим проблемы.

# -*- coding: utf-8 -*-
import subprocess
import os


##saisie du numero de dossier
compostage = str(input('Numero : '))
volume = ('C:')
dossierPrincipal = ('''\\test\\''')
slash = '\\'

##
# Directory 
directory = compostage

# Parent Directory path 
parent_dir = "C:/test/"

#We make only one var for the func
myPath = parent_dir + directory

# Path 
path = os.path.join(myPath) 
##We create a condition to be sure te folder is created
if not os.path.exists(path):
    os.makedirs(path)
    ##We inform the user of the creation of the folder
    print("Directory '% s' well created" % path) 
elif os.path.exists(path):
    ##We inform the user that the folder in question already exists
    print("Directory '% s' already exists" % path) 

##We build the entire path
pathComplet = str(volume+dossierPrincipal+compostage)

##Path verification
print(pathComplet)

##Variable Construction
commandeOuverture = str('('+("""r'explorer """)+'"'+myPath+'"'')')

##Directory verification
print ('La commande est : ', commandeOuverture)

##We open the folder using Popen
subprocess.Popen([commandeOuverture], shell=True)

##We open the folder using Popen if the command above doesn't work
#subprocess.Popen(r'explorer "C:\test\"')

Вывод:

D:\Users\Alex_computer\Documents\Coding\Python\P4_subprocess>main.py
Numero : 5
Directory 'C:/test/5' already exists
C:\test\5
('La commande est : ', '(r\'explorer "C:/test/5")')

D:\Users\Alex_computer\Documents\Coding\Python\P4_subprocess>The specified path was not found.

Это то, что у меня возникает, когда я запускаю скрипт

Я не знаю, что для этого я и пишу здесь на этом форуме

Ответы [ 2 ]

0 голосов
/ 04 апреля 2020

Я думаю, что Pathlib Path может сделать вашу жизнь действительно проще.
Из сообщения об ошибке, которое вы разместили, я понимаю, что вы пытаетесь пройти путь с обычной / ... ('La commande est : ', '(r\'explorer "C:/test/5")') однако windows ОС работает с backsla sh в качестве разделителя пути. В приведенном ниже пути к коду вы сначала печатаете правильный путь windows в переменной pathComplet, однако для своей команды вы используете myPath, который, по-видимому, не имеет правильного разделителя пути.

##Path verification
print(pathComplet)

##Variable Construction
commandeOuverture = str('('+("""r'explorer """)+'"'+myPath+'"'')')

Не могли бы вы попробовать

from pathlib import Path
myPath = Path(myPath)

PS: Извините, что испортил ссылку https://docs.python.org/3/library/pathlib.html

Редактировать:

Полный код, открывший правильный каталог в проводнике для меня:

# -*- coding: utf-8 -*-
import subprocess
from pathlib import Path

##saisie du numero de dossier
directory = str(input('Numero : '))h
parent_dir = Path("C:/test")
myPath = parent_dir / directory

##We create a condition to be sure te folder is created
if not myPath.exists():
    myPath.mkdir()
    ##We inform the user of the creation of the folder
    print("Directory '% s' well created" % myPath)
elif myPath.exists():
    ##We inform the user that the folder in question already exists
    print("Directory '% s' already exists" % myPath)

##Variable Construction
commandeOuverture = "explorer " + str(myPath)

##We open the folder using Popen
subprocess.Popen(commandeOuverture, shell=True)
0 голосов
/ 04 апреля 2020

Попробуйте вручную с помощью команды os.makedirs («Ваш желаемый путь») проверить, возможен ли каталог, который вы хотите создать. Как правило, если вы используете ноутбук компании, создание новых папок в каталоге C: ограничено. Вы можете попробовать создать папку на другом диске или рабочем столе. Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...