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)
Related
I'm running a Conda environment on VSCode and when I Shift-Enter to run main.py , a new Python terminal opens and runs the script, but functions are executing without being called and I'm getting a :
SyntaxError: 'return' outside function
Despite the indentation being seemingly fine.
import math
def h(x):
if x==0:
return 1
else:
return 2*math.sin(x)/x - 1
The above returns:
(base) josh#Joshs-Macbook Coursework1 % source /Users/josh/opt/anaconda3/bin/activate
(base) josh#Joshs-Macbook Coursework1 % conda activate base
(base) josh#Joshs-Macbook Coursework1 % /Users/josh/opt/anaconda3/bin/python
Python 3.8.8 (default, Apr 13 2021, 12:59:45)
[Clang 10.0.0 ] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> return 2*math.sin(x)/x - 1
File "<stdin>", line 1
SyntaxError: 'return' outside function
>>>
You have executed the command of Run Selection/Line in Python Terminal with the shortcut of Shift+Enter. You can select the command of Run Python File in Terminal which is above it.
Shift+Enter is keybindings for Run Selection/Line in Python Terminal, so if you put cursor in the line of return 2*math.sin(x)/x - 1, it will throw errors:
If you want to enter interactive mode then run the function h(x), please
type python in integrated Termial;
import filename. In my case, it's a.py so i import a;
call the function: a.h(any number)
exit interactive mode;
Or you can get result directly by adding print(h(any number)), then clicking the triangle button in top right corner to run python file in integrated Terminal. Get the same result:
run the entire code in python as opposed to the last line.
if you want to run entire scripts:
python3 xxxx.py
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'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.
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.