2

Here is my code:

import subprocess
subprocess.call("rm /home/winpc/Desktop/test.html", shell=True)

This code working properly.I need to do the following change.

file_name="test.html"
dir_path="/home/winpc/Desktop"

I need to remove above file test.html using the variables above mentioned.How can I do that.

Kit
  • 273
  • 3
  • 5
  • 16
  • If you're using `subprocess.call` I'd recommend you capture the exit code and test for success. – cs95 Jul 15 '17 at 14:42
  • 1
    `shell=True` is actively dangerous -- it means that anyone who can control the name of your file can run arbitrary commands on your system. – Charles Duffy Jul 15 '17 at 15:33

2 Answers2

4

First, construct the full file name properly:

full_name = os.path.join(dir_path, file_name)

Then, pass a list as the first argument to call:

subprocess.call(["rm", full_name])

(In real life, you wouldn't use call here at all; you'd use os.remove(full_name).)

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thank you.Problem solved.I need to perform copy command as folow – Kit Jul 15 '17 at 14:49
  • sourse="/home" dest="/home/test" – Kit Jul 15 '17 at 14:50
  • @Kit Open a new question. Actually don't. Just google "how to copy files". – cs95 Jul 15 '17 at 14:57
  • actually I know how to do that.I need to do that using subprocess command.And I need to pass variables inside to the command.@cᴏʟᴅsᴘᴇᴇᴅ – Kit Jul 15 '17 at 15:07
  • @cᴏʟᴅsᴘᴇᴇᴅ. All the people do not have born talent to know each an every code and programming language like you guys .I am still learning.A beginner.Please help. – Kit Jul 15 '17 at 15:13
  • 1
    @Kit It's the same thing: you pass a list whose elements are the name of the command and its arguments: `subprocess.call([cmd_name, arg1, arg2])`. – chepner Jul 15 '17 at 15:26
  • @chepner Thank you for your time and consideration. – Kit Jul 15 '17 at 15:29
  • @Kit I meant the question already exists. You'll find it by googling. – cs95 Jul 15 '17 at 15:36
1

You can use string formatting:

rm_file = "/home/winpc/Desktop/test.html"
subprocess.call("rm {}".format(rm_file), shell=True)

Incidentally I'd recommend not using shell=True where possible; instead pass the arguments as a list:

rm_file = "/home/winpc/Desktop/test.html"
subprocess.call(["rm", rm_file])
kadnarim
  • 177
  • 6
  • 2
    That's more than just a recommendation, but essential for security -- I'd suggest putting the correct/safe/preferred formulation **first** in the answer to make it more prominent. If the user had a file named `/home/winpc/Desktop/$(rm -rf ~).html`... – Charles Duffy Jul 15 '17 at 15:32