I'm a beginner to Python. I've already tried to search for the answer to this question for a long time but had no luck with that. Anyhow here's the code that I want to run (I saved it as test.py):
from sys import argv
script, firstArgument = argv
print "Hello %s!" %firstArgument
It works perfectly fine if I type this into PowerShell:
>> cd ~
>> Python test.py "StackOverflow"
However if I try to type the code into PowerShell like this:
>> cd ~
>> Python
>> from sys import argv
>> script, firstArgument = argv
I get a huge error at that point... I'm just wondering, is there a way to declare argv directly into the PowerShell or is it just not possible?
-Thanks
When you invoke python on its own to get it into interactive mode, there are no arguments passed in. Therefore, argv is empty.
I'm running on Ubuntu, but it's the same general concept in Windows:
:~ $ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from sys import argv
>>> print argv
>>> ['']
Powershell and Python are two separate things, each with their own concepts of the arguments passed to them. Just as a bash script has the concept of passed-in arguments, so too does Powershell, though they are handled differently. However, neither is directly connected to Python's argv.
In general, one can use environment variables to pass things back and forth between Python and the shell (i.e. you could set environment variables inside of Python that could be read in the shell or vice versa, but in either case, these would be different from argv, which is specifically the arguments passed in to the python executable). Or one could use environment variables from the shell to determine what arguments should be passed to python, thereby determining what argv will be.
See this link for more detail: https://docs.python.org/2/library/sys.html#sys.argv
Edit in response to comment from OP:
You can't declare argv, per se. It's representative of how the interpreter was invoked, and in interactive mode, by definition, it has no arguments.
For your specific example, it has to do with the way tuples are unpacked in Python and the current state of argv, which is empty string.
:~ $ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from sys import argv
>>> firstArgument=argv
>>> print firstArgument
['']
>>> firstArgument, secondArgument=argv
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
Since argv only has one element in it, you can't assign it to two variables.
You could, for example, do this:
>>> firstArgument, secondArgument=argv,1
>>> print secondArgument
1
Now there actually are two values -- the tuple ('', 1), and so it can be unpacked into the two different variables.
Related
So I have the following script, test.py:
>cat test.py
def foo(x):
y=x*2
return y
print foo(100)
x = "aaa100"
print x
I can run it well:
>python test.py
200
aaa100
But inside the interactive interpreter, I cannot import it:
>python
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "test.py", line 6, in <module>
x + 10
TypeError: cannot concatenate 'str' and 'int' objects
Do you see what is wrong?
There is already a test module (https://docs.python.org/3/library/test.html or https://docs.python.org/2/library/test.html), which is loaded before your local test.py on the PYTHONPATH because you used import.
In the interpreter, you can see where it is
> import test
> test
<module 'test' from 'C:\Python27\lib\test\__init__.pyc'>
Yours may not be the test module. It tends to successfully import. You must have another test.py on your PYTHONPATH.
Your command line does not have an import, so it is free to use the local filename when you pass it directly to the python executable as an argument.
A simple way to avoid the name conflict, name your file "test_foo.py" and import test_foo. (unless you use test_foo.py in multiple places)
Additionally, consider a run function, in combination with
if __name__ == __main__:
because right now it will execute those prints as part of the import. You will want to do that also in ... whatever other "test.py" you have.
It's either these two cases:
1) Python built-in module "test" (https://docs.python.org/2.7/library/test.html) is being loaded and not your local test.py, however, you shouldn't have any problem importing your local test.py since its a default module, its strange that you are getting an error when you try importing it (unless you have modified it). You can try this to see the imported module cache and check for the test module path
import sys
print sys.modules
If this is the case then you simply have to open a new python interpreter to make sure no test module has been cached. If its still cached, then change the name of your test.py to something_test.py
2) The code you are representing above is not complete and you have a line "x + 10" and since you are assigning x as a string and trying to add integer, your import isn't working. I doubt this being true as I am sure if this was the case you would be aware of it :-)
Here's a minimum working example (MWE), saved as mwe.py:
import sys
def f(n):
print("Testing print()...")
sys.stdout.write("Calculating f({})...".format(n))
When run from the command line I get no output whatsoever:
username#hostname:~/mydir$ python mwe.py 'f(99)'
username#hostname:~/mydir$
When run from within python
I get output (some info removed):
username#hostname:~/mydir$ python
Python 3.5.4 (default, DATE, HH:MM:SS)
[GCC X.X.X Compatible Apple LLVM X.X.X (clang-X.X.X)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from mwe import f
>>> f(99)
Testing print()...
Calculating f(99)...
>>>
Why do these output statements work within python but not from the command line?
python mwe.py 'f(99)' doesn't mean "run the f function from mwe.py with argument 99". If you wanted to do that from the command line, you could execute
python -c 'import mwe; mwe.f(99)'
python mwe.py 'f(99)' means "run the script mwe.py with sys.argv[1] set to the string "f(99)"". The script mwe.py doesn't examine sys.argv or print anything at all; it just defines a function and ends.
This: python mwe.py 'f(99)' just shouldn't work. In this case, 'f(99)' is just passed as an argument to the program.
Try using python -c 'import mwe; mwe.f(99) instead. (also read more about command line usage of python by typing python -h)
is it possible to pass arguments to the python in linux without having a file? I'm currently not able to create a file or change permissions and I don't want to write it inside my code like this:
import sys
sys.argv = ["arg1", "arg2", ...]
I'd like to hand over the arguments while I'm starting the shell:
python <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']
If you are using IPython as interactive shell, you can pass arguments to scripts you run using the %run magic command:
In [1]: %run myscript.py arg1 arg2 ...
(It's not really clear to me what you are trying to achieve, but you probably want to pass the arguments to some script.)
I am getting the following errors when trying to run a piece of python code:
import: unable to open X server `' # error/import.c/ImportImageCommand/366.
from: can't read /var/mail/datetime
./mixcloud.py: line 3: syntax error near unexpected token `('
./mixcloud.py: line 3: `now = datetime.now()'
The code:
import requests
from datetime import datetime,date,timedelta
now = datetime.now()
I really lack to see a problem. Is this something that my server is just having a problem with and not the code itself?
those are errors from your command shell. you are running code through the shell, not python.
try from a python interpreter ;)
$ python
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
[GCC 4.8.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> from datetime import datetime,date,timedelta
>>>
>>> now = datetime.now()
>>>
if you are using a script, you may invoke directly with python:
$ python mixcloud.py
otherwise, ensure it starts with the proper shebang line:
#!/usr/bin/env python
... and then you can invoke it by name alone (assuming it is marked as executable):
$ ./mixcloud.py
Check whether your #! line is in the first line of your python file. I got this error because I put this line into the second line of the file.
you can add the following line in the top of your python script
#!/usr/bin/env python3
I got this error when I tried to run my python script on docker with docker run.
Make sure in this case that you set the entry point is set correctly:
--entrypoint /usr/bin/python
When testing in python shell, I always have to type some import like:
Python 2.5.4 (r254:67916, Jun 24 2010, 15:23:27)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>import sys
>>>import datetime
Can someone help me to automatically finish these? It means I run some command to enter python shell it has already done import for me, and a python shell waiting for me to continue type command.
Thanks.
Try:
python -i -c "import sys; import datetime;"
More info:
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
&
-c cmd : program passed in as string (terminates option list)
Create a file with the commands you want to execute during startup, and set the environment variable PYTHONSTARTUP to the location of that file. The interactive interpreter will then load and execute that file. See http://docs.python.org/tutorial/interpreter.html#the-interactive-startup-file
On a sidenote, you might want to consider ipython as an improved Python shell when working in interactive mode.