This question already has answers here:
What does "sys.argv[1]" mean? (What is sys.argv, and where does it come from?)
(9 answers)
Closed 7 months ago.
I am working my way through "Learning Python the Hard Way". I am totally stumped on "Exercise 13: parameters, unpacking, variables". I'm using Sublime Text 3 in a Windows 7 environment.
Here is my code:
from sys import argv
script, first, second = argv
print ("The script is called:", script)
print ("Your first variable:", first)
print ("Your second variable:", second)
Now my questions:
Do I put this in the scripts folder and then reference this from another .py file something like...
c:\scripts\python\ex11.py one_thing second_thing another_thing
...or do I use a file in my scripts folder to reference my file in another folder that is holding my .py files?
What is the syntax to point to another file in another folder?
It helps to determine what the arguments vector, or argv actually does. It's reading in what you pass in to it from the command line.
So, this means that this command should work (provided Python is in your path, and you can just execute the file in this manner):
C:\scripts\python\ex11.py one_thing second_thing another_thing
Note that you'll only see one_thing and second_thing come across; the first value is the name of the script.
When using the command line to run programs, arguments can be specified to get the program to run in different ways.
In this example, you will need to open up powershell, run cd c:\scripts\python\, and then python ex11.py one_thing second_thing another_thing
Related
This question already has answers here:
When importing a function it runs the whole script?
(2 answers)
Closed 4 months ago.
First of all, please keep in mind I'm no python expert, barely even beyond a beginner.
I have this project in pycharm with multiple files (simply for easier navigation/orginisation), and in one, I'm trying to link to a defined print in another file using "from FILENAME import DEFNAME". But whenever I run the file, it runs the second file first, when it should be running parts of the first file. It doesn't even just run the imported def from the 2nd file, it starts from the very beginning of it.
I wrote it originally about a month ago and left it since then, I swear it worked fine last time, how can I prevent file1 from automatically running file2 in its entireity first while also still being able to call on a def from it?
(Removing the "import" line in file1 fixes it, but also isn't helpful at all lol)
It's simply the normal behavior of Python. When you import a function from a file it will run the whole file. Let's put it in an example:
First File
print("This will run First")
def modified_print():
print("This will run Third")
print("This will run Second")
Second File
from first_file import modified_print
if __name__ == '__main__':
modified_print()
Result
This will run First
This will run Second
This will run Third
You can refer to this question for more details When importing a function it runs the whole script?
This question already has answers here:
How to use argv with Spyder
(4 answers)
Closed last year.
I am struggling with passing 2 arguments in spyder using the command line. I have used the run-->configuration per file and in the command line options put JPEGtoPNG.py/Poxedex/new/. The JPEGtoPNG is the python file and the arguments to be passed are poxedex and new.
Dilemma:
When i run print(sys.argv[0]) it prints:
runcell(0, '/Users/chideraokafor/JPEGtoPNG.py')
which i understand is the default.
However when i run print(sys.argv[1]) it prints:
IndexError: list index out of range.
I have tried everything but still, it's not passing the two arguments, and I really don't want to use pycharm.
If Poxedex and new are command line arguments for a script, JPEGtoPNG.py, execution should be:
python JPEGtoPNG.py Poxedex new
Not / separated.
Note that the error you get is because you are not passing command line arguments and as such sys.argv is a list of length one (that one being the script name) and indexing starts at 0 in Python so accessing the second element via sys.argv[1] is indeed out of range.
Since Spyder provides a Python console and the options you are passing via the menu are intended as that - options and not arguments - you might find it easier to run the script(s) from the command line, for example using VSCode.
Even if you don't want to use VSCode, you can just open a terminal window and invoke the script from there. Just check your environment variables to ensure Python is on your system (or user) path.
This question already has answers here:
how to "source" file into python script
(8 answers)
Closed 3 years ago.
I am struggling to execute a shell script from a Python program. The actual issue is the script is a load profile script and runs manually as :
. /path/to/file
The program can't be run as sh script as the calling programs are loading some configuration file and so must need to be run as . /path/to/file
Please do guide how can I integrate the same in my Python script? I am using subprocess.Popen command to run the script and as said the only way it works is to run as . /path/to/file and so not giving the right result.
Without knowledge of the precise reason the script needs to be sourced, this is slightly speculative.
The fundamental problem is this: How do I get a source command to take effect outside the shell script?
Let's say your sourced file does something like
export fnord="value"
This cannot (usefully) be run in a subshell (as a normally executed script would) because the environment variable and its value will be lost when the script terminates. The solution is to source (aka .) this snippet from an already running shell; then the value stays in that shell's environment until that shell terminates.
But Python is not a shell, and there is no general way for Python to execute arbitrary shell script code, short of reimplementing the shell in Python. You can reimplement a small subset of the shell's functionality with something like
with open('/path/to/file') as shell_source:
lines = shell_source.readlines()
for line in lines:
if line.strip().startswith('export '):
var, value = line[7:].strip().split('=', 1)
if value.startswith('"'):
value = value.strip('"')
elif value.startswith("'"):
value = value.strip("'")
os.environ[var] = value
with some very strict restrictions (let's not say naïve assumptions) on the allowable shell script syntax in the file. But what if the file contained something else than a series of variable assignments, or the assignment used something other than trivial quoted strings in the values? (Even the export might or might not be there. Its significance is to make the variable visible to subprocesses of the current shell; maybe that is not wanted or required? Also export variable=value is not portable; proper Bourne shell script syntax would use variable=value; export variable or one of the many variations.)
If you know what exactly your Python script needs from the shell script, maybe do something like
r = subprocess.run('. /path/to/file; printf "%s\n" "$somevariable"',
shell=True, capture_output=True, text=True)
os.environ['somevariable'] = r.stdout.split('\n')[-2]
to source the entire script in a subshell, then print to standard output the part you actually need, and capture that from your Python script (and assign it to an environment variable if that's what you eventually need to accomplish).
This question already has answers here:
Why does passing variables to subprocess.Popen not work despite passing a list of arguments?
(5 answers)
Closed 1 year ago.
I have a basic batch file that takes user input:
#echo off
set /p Thing= Type Something:
echo %Thing%
pause
However, I'd like to use a variable written in Python to pass into the batch file. Let's say just a string 'arg1' This is just a basic example, but I still cannot figure it out. The below code will run the batch process, but 'arg1' has no impact
import subprocess
filepath = r'C:\Users\MattR\Desktop\testing.bat'
subprocess.call([filepath, 'arg1'])
I have also tried p = subprocess.Popen([filepath, 'arg1']) but the batch file does not run in Python.
I have searched the web and SO, but none of the answers seem to work for me. Here are some links I've also tried: Example 1, Example 2. I've also tried others but they seem fairly specific to the user's needs.
How do I start passing Python variables into my batch files?
Your subprocess likely needs to run with a shell if you want bash to work properly
Actual meaning of 'shell=True' in subprocess
so
subprocess.Popen([filepath, 'arg1'], shell=True)
If you want to see the output too then:
item = subprocess.Popen([filepath, 'arg1'], shell=True, stdout=subprocess.PIPE)
for line in item.stdout:
print line
As a further edit here's a working example of what you're after:
sub.py:
import subprocess
import random
item = subprocess.Popen(["test.bat", str(random.randrange(0,20))] ,
shell=True, stdout=subprocess.PIPE)
for line in item.stdout:
print line
test.bat
#echo off
set arg1=%1
echo I wish I had %arg1% eggs!
running it:
c:\code>python sub.py
I wish I had 8 eggs!
c:\code>python sub.py
I wish I had 5 eggs!
c:\code>python sub.py
I wish I had 9 eggs!
Here is how I managed to call a variable from python to batch file.
First, make a python file like this:
import os
var1 = "Hello, world!"
os.putenv("VAR1", var1) #This takes the variable from python and makes it a batch one
Second, make your batch file, by going to the folder where you want your python program to work, then right-clicking in the map, then create new text file. In this text file, write whatever you want to do with the variable and make sure you call your variable using %...% like so:
echo %VAR1%
Save this file as a batch file like so: file>save as>name_of_file.bat then select: save as file: all files.
Then to call your batch file in python, write:
os.system("name_of_file.bat")
Make sure all these files are in the same map for them to work!
There you go, this worked for me, hopefully I can help some people with this comment, because I searched for so long to find how this works.
PS: I also posted on another forum, so don't be confused if you see this answer twice.
This question already has answers here:
How to read/process command line arguments?
(22 answers)
Closed 8 years ago.
So i've been at this one for a little while and cant seem to get it. Im trying to execute a python script via terminal and want to pass a string value with it. That way, when the script starts, it can check that value and act accordingly. Like this:
sudo python myscript.py mystring
How can i go about doing this. I know there's a way to start and stop a script using bash, but thats not really what im looking for. Any and all help accepted!
Try the following inside ur script:
import sys
arg1 = str(sys.argv[1])
print(arg1)
Since you are passing a string, you need to pass it in quotes:
sudo python myscript.py 'mystring'
Also, you shouldn't have to run it with sudo.