0

I am trying to execute a command on a file such as chmod in a python script. How can I get the file name from command line to the script? I want to execute the script like so ./addExecute.py blah Where blah is the name of some file. The code I have is this:

#!/usr/bin/python
import sys
import os
file = sys.argv[1]
os.system("chmod 700 file")

I keep getting the error that it cannot access 'file' no such file or directory.

1
  • Thanks guys I changed it to: os.chmod (file, 0700) works great now! Commented Dec 3, 2013 at 0:43

4 Answers 4

4
os.system("chmod 700 file")
                     ^^^^--- literal string, looking for a file named "file"

You probably want

os.system("chmod 700 " + file)
                       ^^^^^^---concatenate your variable named "file"
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this isn't a safe way to perform the chmod. Also, Python has os.chmod built in.
1

It could be something like

os.system("chmod 700 %s" % file)

Comments

1
os.system("chmod 700 file")

file is not replaced by its value. Try this :

os.system("chmod 700 " + file)

BTW, you should check if the script was executed with parameters (you could have an error such as "list index out of range")

Comments

0

As pointed out by other answers, you need to place the value of the variable file instead. However, following the suggested standard, you should use format and state it like

os.system("chmod 700 {:s}".format(file))

Using

os.system("chmod 700 %s" % file)

is discouraged, cf. also Python string formatting: % vs. .format.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.