Execute a file with arguments in Python shell
execfile
runs a Python file, but by loading it, not as a script. You can only pass in variable bindings, not arguments.
If you want to run a program from within Python, use subprocess.call
. E.g.
import subprocess
subprocess.call(['./abc.py', arg1, arg2])
Python Shell running file.py with argument
Got it to work:
import runpy, sys
#argv[0] will be replaced by runpy
sys.argv = ['', 'datafile']
runpy.run_path('script.py')
from: https://stackoverflow.com/a/33259769/13840062
Starting a python shell with arguments
While is is questionable if passing commands line arguments to an interactive shell is best practice, it is indeed possible by passing -
instead of the the scripts file name:
$ python - a1 a2
Python 2.7.14 (default, Sep 23 2017, 22:06:14)
[GCC 7.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.argv
['-', 'a1', 'a2']
Executing a shell script with arguments from a python script
You can use
subprocess.Popen(["bash", "pro.sh", "Argument1"])
If your string argument is multiple words, it should work fine.
subprocess.Popen(["bash", "pro.sh", "Argument with multiple words"])
As long as the multiple words are in one string in the list passed to subprocess.Popen()
, it is considered one argument in the argument list for the command.
You should not use shell=True
unless you have a good reason. It can be a security problem if you aren't very careful how it is used.
When running a python script in IDLE, is there a way to pass in command line arguments (args)?
It doesn't seem like IDLE provides a way to do this through the GUI, but you could do something like:
idle.py -r scriptname.py arg1 arg2 arg3
You can also set sys.argv
manually, like:
try:
__file__
except:
sys.argv = [sys.argv[0], 'argument1', 'argument2', 'argument2']
(Credit http://wayneandlayne.com/2009/04/14/using-command-line-arguments-in-python-in-idle/)
Call Python script from bash with argument
To execute a python script in a bash script you need to call the same command that you would within a terminal. For instance
> python python_script.py var1 var2
To access these variables within python you will need
import sys
print(sys.argv[0]) # prints python_script.py
print(sys.argv[1]) # prints var1
print(sys.argv[2]) # prints var2
Passing arguments to Python from Shell Script
If there is space in between argument and argument is not in quotes, then python consider as two different arguments.
That's why the output of print data in the python code is just 1.
Check the below output.
[root@dsp-centos ~]# python dsp.py Dinesh Pundkar
In python code
Dinesh
[root@dsp-centos ~]# python dsp.py "Dinesh Pundkar"
In python code
Dinesh Pundkar
[root@dsp-centos ~]#
So, in your shell script, put $var1 in quotes.
Content of shell script(a.sh):
var1="Dinesh Pundkar"
python dsp.py "$var1"
Content of python code(dsp.py):
import sys
data = sys.argv[1]
print "In python code"
print data
Output:
[root@dsp-centos ~]# sh a.sh
In python code
Dinesh Pundkar
Python: executing shell script with arguments(variable), but argument is not read in shell script
The problem is with shell=True
. Either remove that argument, or pass all arguments as a string, as follows:
Process=Popen('./childdir/execute.sh %s %s' % (str(var1),str(var2),), shell=True)
The shell will only pass the arguments you provide in the 1st argument of Popen
to the process, as it does the interpretation of arguments itself.
See a similar question answered here. What actually happens is your shell script gets no arguments, so $1 and $2 are empty.
Popen will inherit stdout and stderr from the python script, so usually there's no need to provide the stdin=
and stderr=
arguments to Popen (unless you run the script with output redirection, such as >
). You should do this only if you need to read the output inside the python script, and manipulate it somehow.
If all you need is to get the output (and don't mind running synchronously), I'd recommend trying check_output
, as it is easier to get output than Popen
:
output = subprocess.check_output(['./childdir/execute.sh',str(var1),str(var2)])
print(output)
Notice that check_output
and check_call
have the same rules for the shell=
argument as Popen
.
Running a C executable from Python with command line arguments
The >
that you use in your command is a shell-specific syntax for output redirection. If you want to do the same through Python, you will have to invoke the shell to do it for you, with shell=True
and with a single command line (not a list).
Like this:
subprocess.run(f'/home/dev/Desktop/myfile "{inputFileName}" > "{outputFileName}"', shell=True)
If you want to do this through Python only without invoking the shell (which is what shell=True
does) take a look at this other Q&A: How to redirect output with subprocess in Python?
Related Topics
Character Reading from File in Python
Python: Best Practice and Securest Way to Connect to MySQL and Execute Queries
Unpickling a Python 2 Object with Python 3
What Happens When a Module Is Imported Twice
Add Pygame Module in Pycharm Ide
Check If a String in a Pandas Dataframe Column Is in a List of Strings
How to Switch to the Active Tab in Selenium
Can Python Pickle Lambda Functions
Want to Find Contours -> Valueerror: Not Enough Values to Unpack (Expected 3, Got 2), This Appears
Is It Safe to Replace a Self Object by Another Object of the Same Type in a Method
Python: Simple List Merging Based on Intersections
Does Python Have a Bitfield Type
Python: Get the Print Output in an Exec Statement
How to Sort a List of Tuples According to Another List
How to Send Cookies in a Post Request with the Python Requests Library