Trying to use CMD-command in python script with "subprocess.run()" I

Berikut ini adalah pertanyaan dari raficanggih pada mata pelajaran TI untuk jenjang Sekolah Menengah Atas

Trying to use CMD-command in python script with "subprocess.run()"I am trying to run a program I can only access through the CMD in a python script:
command = 'C: \\ Users \\ \\ Documents \\ chatbot.Cli \\ dotnet chatbot.Cli.dll export -f PlainText -p 140 -o "C: \\ Users \\ \\ Documents \\ .txt" --after "2023-05-18 09:00"'

subprocess.run(command, shell=True)
The error I am getting is the following:
'C:\Users\\Documents\chatbot.Cli\dotnet' is not recognized as an internal or external command,
operable program or batch file.
.NET 7.0 is installed and when I run the exact same command on the CMD it works perfectly fine.
Does anyone have an idea why?
Thank you :)

Jawaban dan Penjelasan

Berikut ini adalah pilihan jawaban terbaik dari pertanyaan diatas.

Jawaban:

Sorry if i am wrong

The issue you're experiencing seems to be related to the way you're passing the command to subprocess.run(). In Python, backslashes (\) are used for escaping characters, so they need to be properly escaped within the command string. Additionally, the subprocess.run() function expects the command and its arguments as a list of strings, rather than a single string.

Here's an example of how you can modify your code to properly pass the command to subprocess.run():

import subprocess

command = [

   'C:\\Users\\Documents\\chatbot.Cli\\dotnet',

   'chatbot.Cli.dll',

   'export',

   '-f',

   'PlainText',

   '-p',

   '140',

   '-o',

   'C:\\Users\\Documents\\.txt',

   '--after',

   '2023-05-18 09:00'

]

subprocess.run(command, shell=True)


In the modified code, each part of the command and its arguments are separated into individual strings within the list. The backslashes are properly escaped with an additional backslash (\\), and the command is passed as a list to subprocess.run().

By making these changes, the command should be executed correctly within the subprocess, similar to running it directly in the CMD.

Penjelasan:

Semoga dengan pertanyaan yang sudah terjawab oleh AnswerAiCC dapat membantu memudahkan mengerjakan soal, tugas dan PR sekolah kalian.

Apabila terdapat kesalahan dalam mengerjakan soal, silahkan koreksi jawaban dengan mengirimkan email ke yomemimo.com melalui halaman Contact

Last Update: Sun, 20 Aug 23