How do I get input from linux command line into my Python script?

903 Views Asked by At

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.

4

There are 4 best solutions below

1
On BEST ANSWER
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"
0
On

It could be something like

os.system("chmod 700 %s" % file)
0
On
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")

0
On

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.