Execute a Python script using the command line - python

I want to know how to execute a python script using the command line. This is my code in Arithmetic.py:
def main():
print 'spam'
if __name__ == '__main__':
main()
When I type
python Arithmetic.py
I get an Syntax Error on the "c"
File "ipython-input-11-0770a0dfdadd", line 1
python Arithmetic.py
Any ideas? Thanks!

It looks like you're trying to type the python Arithmetic.py command into an IPython shell. Instead, make sure you're using your operating system's command prompt. (You can get out of a Python or IPython shell by typing exit().)
On Windows, the command prompt looks like this:
C:\Users\Carter>
On Linux, the command prompt looks like this:
carter#carters-computer:~$
In Mac OS X, it looks like this:
Carters-Macbook:~ csande$

To invoke your program from within ipython, use import Arithmetic (no '.py') in the same directory, followed by Arithmetic.main(). You can use the phrase you're currently trying to run your program from a command shell, without first starting an interpreter.

Related

why the same powershell command run on the powershell console but not using os.system?

I would like to include a command to create a 7zip archive withinin a Python script. Since I am working on Windows, I need to pass the command to the powershell console. I am planning to do it with os.system (I am aware that this is not the best way to do it and that I should use subprocess, but I really just need a quick fix and it would not be time effective for me to learn to use a new module in this context).
The following command works if run from the powershell console
&'C:\\Program Files\\7-Zip\\7z' a -mx=0 X:/myarch.zip X:/myarch
So I recreate the same string within python like this:
cmdl = r"&'C:\\Program Files\\7-Zip\\7z' a -mx=0 X:/myarch.zip X:/myarch"
The string is interpreted as follow:
"&'C:\\\\Program Files\\\\7-Zip\\\\7z' a -mx=0 X:/myarch.zip X:/myarch"
Now, if I copy-paste the above string within the powershell console, it runs without problems. However, if I run it within python using os.system(cmdl) I got the following error
"The filename, directory name, or volume label syntax is incorrect"
Why is this the case and how can I fix this issue ?
os.system is meant for executing cmd commands, cmd commands can be ran in powershell maybe after all powershell is a bit advanced but I'm sure that you can't run a cmd command in powershell, henceforth your code is not working.
However a creative solution for executing a powershell command from python(not using python) would be to write your command into a .ps file(powershell script)and then run it using os.startfile()(use this code: os.startfile("script.ps"))

Can't run Python file via Command Prompt, File is not defined error

I am new to Python and currently doing a basic python course to learn. I have been running code all day via the Command Prompt and it has been working fine. For some reason though it has stopped working and python files I try to run are returning the following error:
Traceback (most recent call last):
File "", line 1, in
NameError: name 'hello' is not defined
As per the screen shot and the numbers on it, I performed the following steps in an attempt to run the file:
change to the folder where file is saved
run 'dir' to list all files. I am trying to run 'hello.py'. This contains the code: print('hello simon!')
I can run the file by just typing hello.py into the command prompt, this works ok
I can also run with: python hello.py - this works ok
when I activate Python by typing Python --> Enter, this starts the interpreter ok. However if I then try to run by typing hello.py I get the error message.
This has worked ok all day, I have not changed anything on my PC (to the best of my knowledge!) but just started to get this error a few hours ago. I have looked all over the internet for solution but found nothing. I have uninstalled and re-installed Python, restarted etc... all to no avail.
I am running Python 3.6.5 on a Windows 7 64 bit PC.
It won't let me attach a picture so here is link to screenshot of Command Prompt and error: https://i.stack.imgur.com/BBUe5.jpg
I hope someone can help me with this please
Thankyou
You are not supposed to execute hello.py in the Python Interpreter. It won't work. When you type in python and hit Enter in your Command Prompt, Just type this,
>>> print('hello simon!')
And hit Enter, it would definitely work. Because the interpreter is supposed to execute a code line by line. So if you want to run a Python Script then do not execute it in the Interpreter.
The problem is that when you write python (alone), the command line calls python shell and the following commands are run inside the python shell and not in the command line anymore. Calling a script from the shell has a different format (look it up). You can enter exit() to exit the shell back to command line again
What you are trying to achieve is you are running Hello.py inside Python.
Not with Python.
You need to run Hello.py with Python. As python is interpreter over here.
>>>python
means you are going inside python shell
>>>print('hello simon!')
Is equivalent to your program.
You are running your Python Script as you should and it's working. If you added Python to your path you can run Script you only need to call the Script "hello.py". If you have more than one intepreter, or you didn't added it to your path then you can call it like this "C:\path\to\python\interpretet\pythonxxx.exe" "c:\path\to\python\script.py" you can enven pass arguments to it "C:\path\to\python\interpretet\pythonxxx.exe" "c:\path\to\python\script.py" --argument
When you type python in a shell, then interactive mode is activated. This is like a shell where you type commands and got interpreted right away, in the same way as cmd and powershell works, but for python. This way you can test snippets, or just do simple stuff overly complicated like this
import os
ls = os.listdir(os.path.abspath('c:/'))
def print_dir():
for file in ls:
print(file)
Wich in cmd would be dir c:\ or in powershell ls c:\. The point is that you can test libraries, explore objects, replace the shell or just have fun.

How to execute Python scripts with python command

I want to run the Python Script by using python command from IDLE Python GUI.
The location of the file is C:\Users\DELL\Desktop\Hello.py
When I run python C:\Users\DELL\Desktop\Hello.py with Windows command promt, it works. However, when I try with IDLE Python GUI and Python (command line), it does not work and gives me a message SyntaxError: invalid syntax
Capture
inside python shell, you can import the module. This way, you can see "Hello" printed on shell once u import it.
>>> import sys
>>> sys.path.append('C:\Users\DELL\Desktop')
>>> import Hello
"Hello"
When using IDLE, you are already "inside" python (in its REPL)..
You should "load" (import) the file instead..
See here https://stackoverflow.com/a/21650698/5121955 (exact same situation), where you can find many solutions with their advantages..
You cannot do this from the Python interpreter, since this is not Python syntax, if you want to do this it has to be from command prompt or execute it as a system command:
import os
os.system('python C:\\Users\\DELL\Desktop\\Hello.py')
Or use subprocess.call
If you want to run your python file from another Python file see How can I make one python file run another?
If you want to run it from the IDLE simply select open and navigate to the desired location and select run.
If it is executable script (as you stated, it works from command line with the python command), you should be able to execute it directly from python with the following statements
import os
os.system("C:\\Users\\DELL\\Desktop\\Hello.py")

How can I run Python interpreter in Windows Powershell ISE?

I am a beginner at Python and I am trying to run the Python interpreter from the command line in Windows Powershell ISE.
But here is what I got when I type in python or py:
Instead of
>>>
I got the following (with a line break inbetween):
>
>>
Then the commend line prompt is locked and not responding.
Any help is appreciated!
Are you trying to run a python file (.py) from the command line or run a line of python like 'print('Hello World')'?
If you are trying to run the actual .py file then you will need make sure you are in the same directory of the file then run "python someFile.py" from the command prompt.
If you are trying to just run a function like print('Hello World') then when you are in command prompt and enter "python" you will see the '>>>' as just place holders so you wont be able to erase those. You should now be able to run print('Hello World') and see a result.
Which version of Python are you using and on what platform are you working? One of the best options to start learning Python is Anaconda. Then run Anaconda Prompt and there you can type python and see ">>"!

Run python source file from PowerShell

I'm trying to learn python but have some problem running source files from power shell. When I type 'python' it opens up and I can type python commands directly in the shell. I think this is called interactive mode. But when I try to run/execute a source file I get an error message: It sayys: Syntax error: invalid syntax.
I use 'python myfile.py' when I try to execute the script.
If I run the same file from IDLE it works just fine. Ana idea what I'm doing wrong?
Here is myfile.py. I'm running python 2.7
# filename: myfile.py
while True:
s = raw_input('Enter something: ')
if s == 'Quit':
break
print 'Lenght of the string is', len(s)
print 'Done'
You might have more than one version of Python installed and the version IDLE is using is newer. To see what version of python you have you can type >python -V at a command line. If that version looks appropriate then you might need the full path to the file as the second parameter. E.g >python C:\myfile.py.
If you installed Python correctly there is always a chance that just typing the name of the script will run it with python. E.g. >myfile.py
I always find that adding C:\Python27 to the %PATH% variable and .PY to the %PATHEXT% variable makes running scripts easier. In this case just >myfile should work.
Edit after Update:
Typing just >python with no parameters opens python in 'interactive mode' which is different from the batch or scripting mode that your script is intended for. If executed with arguments the first argument is taken as the file path and further arguments are passed to the script in the sys.argv list.
You will need to put the full path of the Python executable within the command line in order for it to work. You could check and ensure that your python exe is included in your Path among your system variables.
Disclaimer: I don't know PowerShell, but I do know cmd.exe.
I don't know why python myfile.py doesn't work, but assuming that PowerShell bears at least some similarity to cmd.exe, the following should probably work: myfile.py. That's right, just enter the name of the Python script and hit enter.
If you started by typing "python" in powershell you will need to get out of that script.
If you are in python type:
quit()
then type
python myfile.py
This should work if your python is installed correctly.
Try to type this in Powershell:
$env:path="$env:Path;C:\Python33
After this, command
python yourfile.py
should work.
This my sound silly, especially coming from a beginner.
Just save the file on your desktop. Open up powershell and drag the file directly into powershell and it opens. kind of tedious but it works

Categories