问题
I had a small python script that takes input from the command line arguments and done some operations using the inputs taken and display the result
Below is the working example code
some_file.py
import sys
arguments = sys.argv
first_name = sys.argv[1]
second_name = sys.argv[2]
print "Hello {0} {1} !!!!".format(first_name,second_name)
Now i am executing this as
python some_file.py Steve jobs
Result :
Hello Steve Jobs !!!!
Now what all i want is, i don't want to use python command before file name and extension of python file name, that is i want to run the file as a command tool as below
some_file Steve Jobs
so what to do in order to run the python file as above ?
回答1:
Unix-like OS solution: the first line of the file should be #!/usr/bin/python
(or wherever the python interpreter is) and chmod u+x
the script. Run it with ./some_file parameters
.
If you want to launch it with some_file parameters
simply make a link to the script in a directory which is already included into your PATH: sudo ln -s some_file /usr/bin
.
So, here's the full procedure:
blackbear@blackbear-laptop:~$ cat > hw
#!/usr/bin/python
print "Hello World!"
blackbear@blackbear-laptop:~$ chmod u+x hw
blackbear@blackbear-laptop:~$ sudo ln -s hw /usr/bin
blackbear@blackbear-laptop:~$ hw
Hello World!
blackbear@blackbear-laptop:~$
回答2:
make a symbolic link
ln -s some_file.py some_file
now you can type your cmd like this:
some_file Steve Jobs
回答3:
you can run the same program in python shell by using execfile('path')
.
来源:https://stackoverflow.com/questions/17592394/how-to-make-a-python-file-run-without-py-extension